【问题标题】:Push into arrays with setState - React Native使用 setState 推入数组 - React Native
【发布时间】:2021-05-18 14:59:42
【问题描述】:

我是 React Native 的新手,我正在使用来自不同 url 的 api 进行一个项目。当我使用对 url 的获取时,我想用 setState 设置我的状态,但是当我尝试它时,console.warn 显示我的数组 empy。我的代码有什么问题?我感谢任何反馈:)

  constructor() {
    super();

    this.state = {

      location: [],
      current: [],
      condition: [],
      cities: ["london", "paris", "hongkong", "buenos_aires"]
    
    }
  }

  componentDidMount() {

    let fetches = []
    this.state.cities.forEach(
      city => {
        let resp = fetch('http://api.weatherapi.com/v1/current.json?key=10eb2b8701194b128b2122427211005&q=' + city + '&aqi=no').then(res => res.json());
        fetches.push(resp)
      }
    )


    Promise.all(fetches).then(jsonList => {

      jsonList.forEach(
        json => {
          this.setState(state => {
            const location = state.location.concat(json.location)
            const current = state.current.concat(json.current)
            const condition = state.condition.concat(json.condition)

            return {
              location,
              current,
              condition,
            }
          })


        })
    }).catch(function (error) {

      console.error(error)
    })
    console.warn(this.state)
  }

【问题讨论】:

    标签: react-native api push setstate promise.all


    【解决方案1】:

    setState 不会立即更新状态——它会在下一次渲染时更新。假设您实际上是从 API 获取数据,那么您的 console.warn 将显示当前渲染的状态。

    您可以使用回调函数(setState 的第二个参数)查看设置后的值。

    您还可以通过使用数组扩展一次性完成所有更新。

    Promise.all(fetches).then(jsonList => {
      this.setState(state => {
         return {
           location: [...state.location, ...jsonList.map(i => i.location)],
           current: [...current, ...jsonList.map(i => i.current)],
           condition: [...state.condition, ...jsonList.map(i => i.condition)],
         }
      },() => {
         console.log(this.state);
      });
    })
    

    【讨论】:

    • 谢谢你的回答,和你说的完全一样。一旦我渲染它,我在我的状态上设置的一切都在那里!而 tnx 的回调函数和数组传播技巧,都派上用场了。
    • 太好了——您可以使用绿色复选标记将答案标记为正确/已接受,如果您认为它有帮助,您也可以使用箭头进行投票。
    • 我的错,我是 stackoverflow 的新手 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多