1

我的要求是更新 componentWillReceiveProps 的 map 函数中的状态值。

在控制台日志中,我得到的只是 1,但 sub.subscribed 包含 0 和 1

控制台窗口参考:http: //prntscr.com/jqifiz

constructor(props) {
    super(props);
      this.state = {
        regionAll: [],
      };
    }
componentWillReceiveProps(nextProps){
    if(nextProps.apiData !== false ){
      nextProps.apiData.data.datacenter.category.map((sub)=> {
        console.log(sub.subscribed,'sub.subscribed');
        this.setState({
          regionAll: [
            ...this.state.regionAll,
            sub.subscribed
          ]
        },()=>{
          console.log(this.state.regionAll,'sub');
        })
      })
  }

这是在reactjs中更新状态的正确方法吗?

4

2 回答 2

1

出现问题是因为 setState 调用是批处理的,并且您根据 prevState 更新了 React 状态,您应该在这种情况下使用功能状态

componentWillReceiveProps(nextProps){
    if(nextProps.apiData !== false ){
      nextProps.apiData.data.datacenter.category.map((sub)=> {
        console.log(sub.subscribed,'sub.subscribed');
        this.setState(prevState => ({
          regionAll: [
            ...prevState.regionAll,
            sub.subscribed
          ]
        }),()=>{
          console.log(this.state.regionAll,'sub');
        })
      })
  }

但是在地图中调用 setState 是个坏主意,您可以改为从地图中获取数据并调用 setState 一次

componentWillReceiveProps(nextProps){
    if(nextProps.apiData !== false ){
      const subscribed = nextProps.apiData.data.datacenter.category.map((sub)=> {
        console.log(sub.subscribed,'sub.subscribed');
        return sub.subscribed;
      })
      this.setState(prevState => ({
          regionAll: [
            ...this.state.regionAll,
            ...subscribed
          ]
        }),()=>{
          console.log(this.state.regionAll,'sub');
     })
  }
于 2018-06-04T06:36:37.183 回答
1

setState是 async.In Array#map,它调用了多次。只有最后一个值被添加到数组 regionAll 中,而不是全部,因为异步 setState 调用具有多个值。

您可以使用Array#reducer收集sub.subscribed单个数组中的所有值,然后执行状态更新。

if (nextProps.apiData !== false) {

    let sub = nextProps
        .apiData
        .data
        .datacenter
        .category
        .reduce((accum, sub) => [
            ...accum,
            sub.subscribed
        ], [])

    this.setState({
        regionAll: [...sub]
    }, () => {
        console.log(this.state.regionAll, 'sub');
    })
}
于 2018-06-04T06:39:53.750 回答