新对象添加得很好,并使用更新的数据获取 newTodos。在渲染函数中,我得到 this.props.todoList
这是要显示的对象数组。
如何使用 newTodos 更新 todoList 以显示这些新数据?
我可以使用 setState({todoList: newTodos})
来做到这一点,并在渲染函数中获取 this.state.todoList
等,但我不想保持大处于状态的对象( future )。相反,我想使用 Prop 。
有什么建议吗?
var React = require('react');
var TodoList = require('./todo-list.js');
var App = React.createClass({
getInitialState: function () {
return { filter: 'active' };
},
onAdd: function (txt, color) {
console.log('txt: ' + txt + ', color: ' + color);
var newTodos = this.props.todoList.push(Map({ txt: txt, isCompleted: false, color: color }));
this.forceUpdate();
// this.setState(this.state);
},
render: function () {
var { todoList } = this.props;
return (
<div>
<TodoList todoList={todoList}/>
</div>
);
}
});
module.exports = App;
最佳答案
React 中 Props 的唯一目的是将数据从父组件传输到子组件,以便通知它们状态已更改。
您必须维护状态,因为这是控制应用程序组件和维护状态的正确 React 方式完整性。
不知道为什么你更喜欢 Prop 而不是状态,因为无论如何你都必须将数据存储在某个地方,但是只要你添加越来越多的内容,使用forceUpdate()提供的解决方案很快就会使你的应用程序状态不一致组件。
关于javascript - React.js : Re-render component data on add,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556933/