考虑我的组件方法
clickRunButton() {
this.props.resetTaskBatch({
tasks: threeSampleTasks,
busy: true
});
// In this method this.props.taskBatch.tasks should have three items
this.performTasks();
}
问题是this.props.taskBatch在performTasks方法中为空。使用setTimeout进行测试会得到有趣的结果。我需要了解一些关于react / redux的异步内容吗?
clickRunButton() {
this.props.resetTaskBatch({
tasks: threeSampleTasks,
busy: true
});
// zero objects in tasks key
console.log(this.props.taskBatch);
// three objects in task key after 100 ms!!
setTimeout(function() { console.log(this.props.taskBatch); }.bind(this), 100);
// but I need them right away here
this.performTasks();
}
我该如何解决这个问题? 谢谢!
<小时/> UPDATE 这是reducer
const initialState = {
tasks: [],
busy: false
}
export default function (state = initialState, action) {
switch (action.type) {
case 'TASK_BATCH_RESET':
var taskBatch = Object.assign({}, action.payload);
return taskBatch;
break;
case 'TASK_BATCH_UPDATED':
var taskBatch = Object.assign({}, action.payload);
return taskBatch;
break;
default:
return state;
}
}
答案 0 :(得分:1)
更新redux存储就像setState一样异步发生,因此在调度更新存储的操作后调用this.performTasks将没有正确的数据,
您有两个选项,要么从调度的操作返回一个promise,要么在componentDidUpdate
函数中执行操作(根据laster RFC到React,componentWillReceiveProps将从版本17开始不再使用,并重命名为{{ 1}})因此鼓励在componentDidUpdate中采取必要的行动
UNSAFE_ComponentWillReceiveProps
或
componentDidUpdate(prevProps, prevState) {
if(!_.isEqual(this.props.taskBatch.tasks, prevProps.taskBatch.tasks) {
this.performTasks();
}
}