ReactJS:道具无法立即获得
ReactJS: Props not available immediately?
本文关键字:ReactJS 更新时间:2023-10-22
我有一个React组件,当它被挂载时,它需要访问一个道具。实际上,我在getInitialState()中使用了一个prop来定义正确的状态,但由于它可能是一个反模式,我也尝试在componentWillMount/componentDidMount中访问它,但在生命周期的这一点上它总是空的。
下面是一个简短的例子:
// MyComponent
module.exports = React.createClass({
propTypes: {
projectId: React.PropTypes.number,
customerId: React.PropTypes.number
},
getDefaultProps() {
return {
projectId: null,
customerId: null
}
},
componentWillMount() {
this.getNamespace()
},
componentDidMount() {
this.getNamespace()
},
getNamespace() {
var str = "items"
if (this.props.customerId) str += "_c" + this.props.customerId
if (this.props.projectId) str += "_p" + this.props.projectId
// this.props.projectId is always empty here
// this.props.customerId is always empty here
// so str is always "items"
console.log("NS is " + str)
console.log(this.props)
return str
},
render() {
return (
<AppModule />
)
}
})
// Usage:
<MyComponent customerId="1" projectId="2" />
为什么getInitialState、componentWillMount和componentDidMount中this.props.projectId和this.props.customerId始终为空?我做错了什么?我应该如何解决?不想只使用脏的setTimeout并等待:)
哦,在我忘记之前:我其实可以使用这些道具。但不是在这个状态。此外,调用我的组件的组件不会刷新道具或类似的东西。至少我是这么认为的。
谢谢你的帮助!
我也遇到了同样的问题,我希望道具能立即可用,但它们似乎不太可能,因为它们来自一个依赖(相对)长时间运行的外部调用来构建这些道具的父级。使用componentDidMount对我不起作用,但componentWillReceiveProps确实起到了很好的作用。我认为您可以从那里调用getNamespace。
这应该有效:)
if (this.props.customerId) str += "_c" + this.props.customerId
此外,我认为您不会访问componentWillMount中的道具。
但我想知道,你在哪里定义道具值
相关文章:
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 拨打'父亲'函数形式a'儿童'ReactJS中的组件
- ReactJS映射:如何仅在url变量不为空时呈现html链接
- 如何更改reactjs中外部/独立组件的状态或属性
- ReactJS和SpringDataRest缓存问题可能与websocket有关
- reactjs this.refs vs document.getElementById
- 同构reactjs-cdn资产
- 在ReactJS中重新渲染孩子3次可以接受吗
- 如何在ReactJs中显示Json数据
- 将IndexedDB中的数据拉入数组,并通过ReactJS输出
- 如何在ReactJs中渲染子组件时重新加载子组件的数据
- 如何在ReactJs中链接下拉列表和文本区域
- 如何在ReactJs中呈现选定选项的更改表
- 在select上呈现不同形式的reactjs
- onClick事件未触发reactjs
- 如何在ReactJs中渲染重音符号
- reactjs无法将this.pops传递到react图表列表中
- 在reactjs组件中预加载数据
- ReactJS中动态生成的输入文本字段值设置问题
- 从外部函数渲染后更改ReactJS类的状态