反应切换列表竞争条件?

React switching lists race condition?

我正在尝试实现一个队列,用户可以在其中将项目从一个列表切换到另一个列表。即从 "available" 到 "with client",其中队列的状态保存在根 React 组件中,如下所示:

this.state = {
  queue: {
    available: [{ name: "example", id: 1 }, ...],
    withClient: [],
    unavailable: []   
  }
};

但是我的移动功能坏了:

move(id, from, to) {
  let newQueue = deepCopy(this.state.queue);
  console.log("NEW QUEUE FROM MOVE", newQueue); // { [from]: [], [to]: [undefined] }
  console.log("QUEUE IN STATE FROM MOVE", this.state.queue); // { [from]: [{...}], [to]: [] }
  let temp = newQueue[from].find(x => x.id === id);
  newQueue[from] = this.state.queue[from].filter(x =>
    x.id !== id
  );
  newQueue[to] = this.state.queue[to].concat(temp);
  this.setState({
    queue: newQueue
  });
}

我希望 2 console.logs 是一样的。这里似乎发生了某种我不理解的竞争条件。它导致出现错误 Cannot read property 'id' of undefined

现在唯一的方法是从 "Available" 列表中的每个项目中包含的 HelpedButton 组件触发移动,该组件获得传递的道具:

class HelpedButton extends React.Component {
  constructor() {
    super();
    this.clickWrapper = this.clickWrapper.bind(this);
  }

  clickWrapper() {
    console.log("I have id right?", this.props.id); //outputs as expected
    this.props.move(this.props.id, "available", "withClient");
  }

  render() {
    return (
      <span style={this.props.style}>
        <button onClick={this.clickWrapper}>
          <strong>Helped A Customer</strong>
        </button>
      </span>
    );
  }
}

export default HelpedButton;

我不认为 deepCopy 函数有什么问题,但这里是从 node_modules:

导入的文件
"use strict";

function deepCopy(obj) {
  return JSON.parse(JSON.stringify(obj));
}

module.exports = deepCopy;

react documentation 推荐的使 setState 取决于先前状态的方法是使用看起来像这样 setState((prevState,prevProp)=>{}) 的更新程序表单。使用此方法,您的 move 函数将如下所示。

move(id, from, to) {

  let temp = newQueue[from].find(x => x === x.id);
  newQueue[from] = this.state.queue[from].filter(x =>
    x.id !== id
  );
  newQueue[to] = this.state.queue[to].concat(temp);
  this.setState((prevState)=>{
    queue: {
      ...prevState.queue,
      [from]: prevState.queue[from](o => x.id !== id),
      [to]: [from]: prevState.queue[from].concat(prevState.queue[from].find(x => x === x.id))
    }
  });
}

我相信您看到不同输出的原因是 console.log 输出一个实时对象,这意味着如果您 运行 console.log(obj) 之后更改 obj 参数,则显示的参数是更改。尝试使用 console.log("obj: " + JSON.strignify(obj)).
进行调试 这里有更多关于为什么在依赖 react docs

中的先前状态时应该调用 setState 的异步方法