Reactjs redux中调度操作的延迟
调用dispatch,并立即控制台记录数据。它显示的是旧数据而不是更新的数据,除非您在中添加一些延迟 示例基于redux todo示例 行动Reactjs redux中调度操作的延迟,reactjs,redux,Reactjs,Redux,调用dispatch,并立即控制台记录数据。它显示的是旧数据而不是更新的数据,除非您在中添加一些延迟 示例基于redux todo示例 行动 let nextTodoId = 0 export const addTodo = text => { console.log('action'); return ({ type: 'ADD_TODO', id: nextTodoId++, text }) } 减速器 const todos = (state =
let nextTodoId = 0
export const addTodo = text => {
console.log('action');
return ({
type: 'ADD_TODO',
id: nextTodoId++,
text
})
}
减速器
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
console.log('reducer');
return [
...state,
{
id: action.id,
text: action.text,
completed: false
}
]
default:
return state
}
}
export default todos
组成部分
class AddTodo extends Component {
render() {
var _this = this;
return (
<div>
<form
onSubmit={e => {
e.preventDefault()
this.props.dispatch(addTodo('input.value'))
console.log('Not updated', this.props.todos);
setTimeout(function() {
console.log('Updated', _this.props.todos);
});
}}
>
<button type="submit">Add Todo</button>
</form>
</div>
);
}
}
AddTodo.js:18 Updated[{…}]当您调度一个操作时,存储状态由reducer更新,然后您的mapStateToProps函数从存储返回更新的状态 这是预期的行为,而不是在提交时将其记录在渲染中
render() {
console.log(this.props.todos)
.... // remaining code
}
希望它有帮助对一个操作进行争议是异步的。您需要使用MapStateTops从组件中的存储中获取状态。您可以使用componentWillReceiveProps获取更新的存储数据。更新的值将在下一次渲染中可用。无论何时更新“todos”存储,使用该信息的组件都会对该更改作出反应。你在哪里使用待办事项列表?
render() {
console.log(this.props.todos)
.... // remaining code
}