我对Reactive&Redux相当陌生,而且我还在和rerender机修工做斗争。
我正在编写一个简单的ToDo应用程序。这是我的ToDoList
课程:
class ToDoList extends Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
todoList: this.sortTodos(props.todoList)
};
}
render = () => {
return (
<List>
{this.state.todoList.map((todoItem, index) =>
<ToDo key={index} info={todoItem} />
)}
</List>
);
}
componentWillMount = () => {
if (this.state.todoList.length === 0)
this.props.loadToDoList();
}
componentWillReceiveProps = (nextProps: Props) => {
this.setState({ todoList: this.sortTodos(nextProps.todoList) });
}
sortTodos = (todos: ToDoModel[]) => {
return todos.sort((a, b) => a.completed === b.completed ? 0 : a.completed ? 1 : -1)
}
}
当我检查一个todo时,我的ToDoModel
被更新,componentWillReceiveProps
被调用。
我试图计算已完成的待办事项数量,并在componentWillReceiveProps
中的状态中设置这个数字。但是,由于某种原因,我的待办事项列表不会按更新的顺序重新排列,即使函数末尾有一个this.forceUpdate()
。(实际上,直到我重新加载屏幕,才会检查和重新排序我的待办事项。)
我遗漏了什么?
发布于 2018-03-27 02:21:47
可能是因为key
在Todo
项目中。尝试将键设置为项的id
<List>
{this.state.todoList.map((todoItem, index) =>
<ToDo key={todoItem.id} info={todoItem} />
)}
</List>
发布于 2018-03-27 02:17:58
内部映射试图返回组件:
{this.state.todoList.map((todoItem, index) =>
return <ToDo key={index} info={todoItem} />;
)}
https://stackoverflow.com/questions/49510066
复制