React选择性地不将新道具传递给渲染对象
React selectively not passing new props to rendered object
我正在开发一个多阶段表单,该表单基于本指南通过AJAX获取一些中间数据。我遇到了一个奇怪的问题,React没有向组件传递新道具。
// MyForm.js.jsx
var MyForm = React.createClass({
render: function() {
switch(this.state.stage) {
case 1:
return <InitialFields
nextStage={this.nextStage}
save={this.save}
/>
case 2:
return <ChoiceFields
title="Choose first thing:"
field="first_id"
options={this.state.firstChoices}
nextStage={this.nextStage}
save={this.save}
/>
case 3:
return <ChoiceFields
title="Choose second thing:"
field="second_id"
options={this.state.secondChoices}
nextStage={this.nextStage}
save={this.save}
/>
}
}
// etc ...
});
ChoiceFields.js.jsx:
var ChoiceFields = React.createClass({
render: function() {
console.log(this.state);
var options = this.setOptions();
return (
<div className="choiceFields">
<h1>{this.props.title}</h1>
<SearchBar onChange={this.onSearch} />
<div className="btn-group">{options}</div>
<NextButton next={this.saveAndContinue} text="Set Default Values" />
</div>
);
},
setOptions: function() {
var buttons = this.state.options;
return buttons.map(function(choice) {
return (
<ChoiceButton key={choice.id} title={choice.name}
description={choice.description} id={choice.id}
makeSelection={this.selectButton} selected={choice.selected}
/>
);
}.bind(this));
}
});
当状态从1前进到2时,它会毫无问题地呈现ChoiceFields。当状态从2前进到3时,它会渲染新标题,但options
道具保持不变,尽管给了它一个不同的对象。
有没有办法强制React更新道具,或者以其他方式重新发送ChoiceFields
对象?
--更新--
我将this.props.options
复制到this.state.options
中,并使用state跟踪是否选择了某个选项。根据@supell的建议,我将对象数组保存在props
中,并计算在渲染方法中选择了哪一个。这解决了问题。
根据注释,您正在将道具复制到getInitialState中ChoiceFields组件中的状态。当道具更新时,不会再次调用getInitialState,因此您只能看到过时的状态。您可以将componentWillReceiveProps函数添加到ChoiceFields,该函数可以从新道具更新状态。或者,您可以进行重构,根本不将道具复制到状态,因为这是React调用的特定反模式。
您可以选择的另一个选项是为ChoiceField
变体提供不同的密钥,这样React就会知道它们是不同的实例,当您在后续渲染中交换它们时,它们将获得完整的组件生命周期:
case 2:
return <ChoiceFields
key="first"
title="Choose first thing:"
field="first_id"
options={this.state.firstChoices}
nextStage={this.nextStage}
save={this.save}
/>
case 3:
return <ChoiceFields
key="second"
title="Choose second thing:"
field="second_id"
options={this.state.secondChoices}
nextStage={this.nextStage}
save={this.save}
/>
React.js和Dynamic Children-Why the Keys are Important对发生的事情有很好的解释,并链接到相关文档。
- AngularJs指令,该指令创建内部有数据对象的新指令
- javascript处理一个对象数组以获得一个新的对象数组
- 如何在javascript上向数组的对象添加新元素
- underline-js:将键对象与数组键对象进行比较,如果存在,则移除现有的添加新的
- 查找关键字并创建新对象
- 从自身的一个版本中创建新的JavaScript对象
- 创建新对象时,为什么要更新旧对象
- 为什么要使用立即调用的函数来创建新对象
- 剑道网格-插入具有外部列的新对象失败
- 将原型调用为新对象中的另一个原型
- 在对象上迭代.解构其键和属性并添加新的键和属性
- 将新对象添加到本地存储
- 为什么shouldComponentUpdate说当前道具是React中的新道具
- 反应:如何将当前的道具儿童与新道具儿童进行比较
- React选择性地不将新道具传递给渲染对象
- 如何在不破坏shouldComponentUpdate的情况下传递对象/子对象作为道具
- React Native接收新道具,componentWillReceiveProps
- 如何在React 0.14中使用新道具在顶层再次渲染组件
- 如何给出指向对象新实例化的指针
- 当使用新道具调用渲染时,React JS没有完全更新视图