我对React有点陌生,遇到了一个问题,在组件、子组件和外孙中,我得到了一些未定义的道具。
我现在要做的是..。
app.jsx
constructor(props) {
super(props);
this.state = {
entities: [],
}
}
componentDidMount() {
axios.get(`api.com`)
.then(response => {this.setState({entities: response,})});
}
render() {
return (
<div>
<Component entities={this.state.entities} />
</div>
);
}
据我所知,一旦组件挂载,它就执行axios调用,并设置状态。然后将state.entities传递到组件中。
然后,我需要在组件呈现之前访问支持,那么我是在componentWillMount()中这样做,然后将组件状态设置为作为道具传递给ChildComponent吗?
componentWillMount() {
var getEntities = this.props.entities
this.setState({entities:getEntities})
}
render() {
return (
<div>
<ChildComponent entities={this.state.entities} />
</div>
);
}
最后,我的问题在于我的ChildComponent,或者GrandChildComponent --在设置道具或状态之前,所有东西都是呈现的。因此,当我调用{entities.id}时,我得到一个未定义的。
也许我只是个傻瓜?
发布于 2018-03-23 15:20:17
使用componentWillReceiveProps
生命周期。
在componentDidMount
中设置父组件中的状态时,它会重新呈现子组件和子组件.
componentWillReceiveProps(nextProps) {
if(nextProps.entities){
this.setState({entities:nextProps.entities})
}
}
componentWillMount
只在初始呈现时调用,而不是对每次重新呈现时调用,在您的情况下,需要处理重呈现。
发布于 2018-03-23 15:33:02
你的密码在我看来不错。我看到的唯一问题是在没有检查的情况下将道具显式地传递到子组件中。当您的数据正在获取时- states
等于[]
,并将其传递给子组件。我将添加布尔状态,例如isFetched
,当请求完成时,将其设置为true。当数据正在获取时,您可以显示loading
。下面的例子。
state = {
entities: [],
isFetched: false
}
...
componentDidMount() {
axios.get(`api.com`)
.then(response => {this.setState({entities: response, isFetched: true})});
}
...
render(){
const {isFetched, entities} = this.state
return (
<div>{isFetched ? <ChildComponent {entities}> : 'Loading...'}</div>
)
}
const ChildComponent = ({entities}) => (<div>{JSON.stringify(entities)}</div>)
希望这有意义。
发布于 2018-03-23 15:23:35
您正在使用响应设置状态。您可以/应该使用来自API
端的数据设置状态。
在componentWillMount()
中,您必须获取数据并使用数据参数设置状态,而不是润湿响应。
componentWillMount() {
axios.get(`api.com`)
.then(response => response.json())
.then((data) => this.setState({entities: data}))
}
在设置状态之前,始终可以执行console.log()
。
componentWillMount() {
axios.get(`api.com`)
.then(response => response.json())
.then((data) => console.log('this is entities data', data))
}
希望这可能对你有帮助。
https://stackoverflow.com/questions/49452898
复制相似问题