Parent( MyList
在我的示例中)组件通过 Child( MyComponent
)组件呈现数组。父决定更改数组中的属性,React 触发子重新渲染的方式是什么?
在调整数据后,我在 Parent 中想到的是 this.setState({});
。这是触发更新的 hack 方式还是 React 方式?
JS 小提琴: https ://jsfiddle.net/69z2wepo/7601/
var items = [
{id: 1, highlighted: false, text: "item1"},
{id: 2, highlighted: true, text: "item2"},
{id: 3, highlighted: false, text: "item3"},
];
var MyComponent = React.createClass({
render: function() {
return <div className={this.props.highlighted ? 'light-it-up' : ''}>{this.props.text}</div>;
}
});
var MyList = React.createClass({
toggleHighlight: function() {
this.props.items.forEach(function(v){
v.highlighted = !v.highlighted;
});
// Children must re-render
// IS THIS CORRECT?
this.setState({});
},
render: function() {
return <div>
<button onClick={this.toggleHighlight}>Toggle highlight</button>
{this.props.items.map(function(item) {
return <MyComponent key={item.id} text={item.text} highlighted={item.highlighted}/>;
})}
</div>;
}
});
React.render(<MyList items={items}/>, document.getElementById('container'));
原文由 Djam 发布,翻译遵循 CC BY-SA 4.0 许可协议
这里的问题是您将状态存储在
this.props
而不是this.state
。由于此组件正在发生变化items
,items
处于状态并且应存储在this.state
中。 (这是 一篇关于道具与状态的好文章。)这解决了您的渲染问题,因为当您更新items
时,您将调用setState
,这将自动触发重新渲染。这是您的组件使用状态而不是道具的样子:
请注意,我将
items
道具重命名为initialItems
,因为它清楚地表明MyList
会改变它。这是 文档推荐的。你可以在这里看到更新的小提琴: https ://jsfiddle.net/kxrf5329/