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中的道具。

但我想知道,你在哪里定义道具值