私は、取り付けられたときに小道具にアクセスする必要があるReactコンポーネントを持っています。実際、私はgetInitialState()で適切な状態を定義するために小道具を使用していますが、それは反パターンかもしれないので、私はcomponentWillMount/componentDidMountにもアクセスしようとしましたが、ライフサイクルのこの時点では常に空です。ReactJS:小道具はすぐに利用できませんか?
ここを短縮例です:
// 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を使用して待機したくない:
ああ、私が実際にこれらの小道具を使うことができる。しかし、この状態ではありません。また、私のコンポーネントを呼び出すコンポーネントは、そのような小道具などをリフレッシュしません。少なくとも私はそう思う。
ありがとうございました!
'React.createClass'と組み合わせて 'componentWillMount:function()'の代わりにES6( 'componentWillMount()'が混在しているようです。私は以前これを見たことがないので、これが問題を引き起こすかどうかはわかりません。さらに、JSX属性で数値を渡す場合は、 'customerId = "1"'の代わりに 'customerId = {1}'を使用する必要があります。 –