javascript - 数组填充异步?(反应功能意外)
问题描述
我有一个结构如下的 React 组件:
class SearchElement extends React.Component{
constructor(props){
super(props);
this.state = {
otherArray: [],
testArray: [],
}
this.handleClick = this.handleClick.bind(this);
}
otherEvent = (event) => {
this.setState( { otherArray:event.target.value }, this.handleClick);
}
handleClick() {
const { otherArray } = this.state;
var exampleArray = [];
console.log("THIS SHOULD BE EMPTY");
console.log(exampleArray);
console.log("exampleArray already has elements in it");
//...
//changes made to exampleArray
this.setState({ testArray: exampleArray });
}
通过单击 HTML 按钮调用 otherEvent,然后该按钮应调用 handleClick 作为 setState 调用中的回调函数。然而,当打印语句显示 exampleArray 不知何故已经有元素(而且它也不是正确的元素)。如果相关,我正在使用 NextJS。我假设我对异步调用或如何维护 React 状态感到困惑。如果我应该提供更多信息,请告诉我。
谢谢!
解决方案
推荐阅读
- java - 使用有状态处理计算 Apache Beam 中的增量
- for-loop - OpenMP 嵌套 for 循环
- powershell - 导入 CSV 按 EmployeeID 属性查找 AD 帐户并导出到 CSV
- php - 如何使用模式按单个行编辑/删除表格?
- r - 使用 merge() 和空白合并数据帧 - 格式问题
- laravel - 我可以在查询中使用 Mutators 吗?
- python - 芹菜@task_postrun.connect没有触发
- jquery - jQuery和IE 11“in”的操作数无效
- docker - Docker:来自 ubuntu 的 bash 中的 df -h 输出
- php - Laravel:从表用户获取名称