【问题标题】:setState in map function of reactreact的map函数中的setState
【发布时间】:2018-11-13 10:02:33
【问题描述】:

我的要求是更新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 中更新状态的正确方法吗?

【问题讨论】:

  • 那么问题是什么
  • @Isaac 设置状态没有正确更新
  • 您的控制台快照打印 ["1"] "sub"。但我可以看到 console.log(this.state.regionAll,'subbbb');这个说法 。可能是您在不同的位置进行检查。你的代码看起来不错
  • @stack26 抱歉,我更新了该代码并将 subbb 替换为 sub
  • 控制台状态非常好

标签: reactjs react-redux react-state-management


【解决方案1】:

setState 是异步的。在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');
    })
}

【讨论】:

  • 如果我想更新所有状态数组上的单个值。如何执行? this.setState({ regionAll: true });
【解决方案2】:

出现问题是因为 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');
     })
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-08
    • 2020-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多