首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在多级构件树中访问渲染后的支持-- React

在多级构件树中访问渲染后的支持-- React
EN

Stack Overflow用户
提问于 2018-03-23 15:11:57
回答 4查看 1.1K关注 0票数 0

我对React有点陌生,遇到了一个问题,在组件、子组件和外孙中,我得到了一些未定义的道具。

我现在要做的是..。

app.jsx

代码语言:javascript
运行
复制
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吗?

代码语言:javascript
运行
复制
componentWillMount() {
    var getEntities = this.props.entities
    this.setState({entities:getEntities})
  }

render() {
  return (
    <div>
      <ChildComponent entities={this.state.entities} />
    </div>
  );
}

最后,我的问题在于我的ChildComponent,或者GrandChildComponent --在设置道具或状态之前,所有东西都是呈现的。因此,当我调用{entities.id}时,我得到一个未定义的。

也许我只是个傻瓜?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-03-23 15:20:17

使用componentWillReceiveProps生命周期。

componentDidMount中设置父组件中的状态时,它会重新呈现子组件和子组件.

代码语言:javascript
运行
复制
componentWillReceiveProps(nextProps) {

        if(nextProps.entities){

           this.setState({entities:nextProps.entities})
        }
    }

componentWillMount只在初始呈现时调用,而不是对每次重新呈现时调用,在您的情况下,需要处理重呈现。

票数 1
EN

Stack Overflow用户

发布于 2018-03-23 15:33:02

你的密码在我看来不错。我看到的唯一问题是在没有检查的情况下将道具显式地传递到子组件中。当您的数据正在获取时- states等于[],并将其传递给子组件。我将添加布尔状态,例如isFetched,当请求完成时,将其设置为true。当数据正在获取时,您可以显示loading。下面的例子。

代码语言:javascript
运行
复制
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>)

希望这有意义。

票数 1
EN

Stack Overflow用户

发布于 2018-03-23 15:23:35

您正在使用响应设置状态。您可以/应该使用来自API端的数据设置状态。

componentWillMount()中,您必须获取数据并使用数据参数设置状态,而不是润湿响应。

代码语言:javascript
运行
复制
componentWillMount() {
  axios.get(`api.com`)
  .then(response => response.json())
  .then((data) => this.setState({entities: data}))
}

在设置状态之前,始终可以执行console.log()

代码语言:javascript
运行
复制
componentWillMount() {
  axios.get(`api.com`)
  .then(response => response.json())
  .then((data) => console.log('this is entities data', data))
}

希望这可能对你有帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49452898

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档