【发布时间】:2019-05-19 00:11:57
【问题描述】:
目前
我有一个子组件 ItemField(参见下面的代码),它从父组件获取 this.props.itemId,并检查是否填充了 this.props.itemId,并根据检查即
itemId = this.props.itemId ? this.props.itemId : "new";
问题
在应用程序上移动项目列表中项目位置的排序操作,导致this.props.itemId 和this.itemId 返回控制台日志确认的不同值。 this.props.itemId 具有正确的值,但 this.itemId 包含该位置项的原始值。
ItemField.js
class ItemField extends Component {
constructor(props) {
super(props);
this.state = {
//temp value of inputs
}
}
componentDidMount() {
//no actions on did mount
}
//issueId to be Updated
//if "new", then a new issue will be updated
itemId = this.props.itemId ? this.props.itemId : "new";
render() {
console.log("this.props.itemId = " + this.props.itemId); //logs "1111"
console.log("this.itemId = " + this.itemId); //should log "1111" i.e. same as above, but this doesn't always happen
return (
<div
id={this.itemId}
>{showValue}
</div>
)
}
}
export default ItemField;
问题
我在上面的脚本中有 2 个 console.log 行,在某些情况下(例如,在对项目列表进行排序之后)返回不同的值。这些应该始终相同。这可能是什么原因?
注意事项:
- 我尝试将
itemId = this.props.itemId ? this.props.itemId : "new"行移到构造函数和componentDidMount 中,但这并没有解决问题。 - 我没有映射父组件中的所有 ItemField,而是为每个组件显式创建一个组件,例如
<ItemField value={this.props.item.name} itemId={this.props.item.id} />其中name是字段值,id是传递给所有字段的 itemId。
组件结构
【问题讨论】:
-
能否复制父组件中
ItemFields 映射的部分? -
我目前没有映射所有
ItemFields,而是明确地为每个人创建一个组件,例如<ItemField value={this.props.item.name} itemId={this.props.item.id} />其中name是字段值,id是传递给所有字段的itemId。 -
@Wronski 有点像在黑暗中拍摄,但您是否考虑过在渲染方法中移动 itemId 定义?常量 itemId = this.props.itemId ? this.props.itemId : "新";
-
@ChristopherNgo,这是我最初的想法,但我认为有一种更简洁的方法可以做到这一点,代码的读者可以看到渲染上方组件的所有变量。仅供参考,我进行了重构(即在渲染中计算的变量),它可以工作:P
标签: reactjs