【问题标题】:How to make an http call in parent component to setState and then send the state to all child components?如何在父组件中对 setState 进行 http 调用,然后将状态发送给所有子组件?
【发布时间】:2020-07-22 16:13:05
【问题描述】:

所以我正在尝试从父级的 componentDidMount() 调用 axios.get('{link here}'):

class Parent extends React.Component {
constructor(){
   super();
   this.state = {
       stuff: []
   }
}

componentDidMount() {
     axios.get({link})
     .then(res => {
         this.setState({stuff: res.data}) 
     }
}

render() {
    return(
    <Child stuff={this.state.stuff} />
    )
}

然后是Child各种子组件,其中一个是这样的:

class Child extends React.Component {
    constructor(props) {
         super(props);
    }

    render() {
       return(
           //To access everything in the data of parent here in child component
       )    
}

即使父母在 console.log() 中显示数据,孩子也没有收到任何东西

【问题讨论】:

  • 在您的 axios 调用中添加 .catch。代码似乎没问题,所以也许 axios 调用失败了。

标签: javascript json reactjs axios


【解决方案1】:

Child 类中,您可以访问使用this.props 传递下来的道具。它看起来像这样:

class Parent extends React.Component {

  state = {
    name: 'Felix'
  }

  render() {
    return (
      <Child name={this.state.name} />
    )
  }
}


class Child extends React.Component {

  render() {
    return <p>My Name is {this.props.name}</p>
  }
}

ReactDOM.render(<Parent />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

如果子组件不打算保持内部状态,那么您可以将其重构为功能组件:

function Child(props) {
  return <p>My Name is {props.name}</p>
}

更多关于函数和类组件的信息here

【讨论】:

  • 在发出http请求后,值会更新,但传递给孩子的是相同的初始值,新值永远不会被发送。我该如何解决这个问题?
  • 如果实际正在检索数据,请在子组件中添加{JSON.stringify(this.props.stuff)}。这将帮助您可视化数据结构。
【解决方案2】:

不确定它是否是整个解决方案,但替换

constructor(){
   super();
   this.state = {
       stuff=[]
   }
}

通过

constructor(){
   super();
   this.state = {
       stuff: []
   }
}

您在对象声明中有一个= 符号。

【讨论】:

  • 很抱歉,这只是一个打字错误。我的目标是,来自父级的单个 HTTP 调用及其获取的数据可以传递给所有子级 { 数据,如公司、客户、产品,所有这些都来自 HTTP 调用},所以而不是在我想要的每个组件中发出请求在父级中发出单个请求,然后传递值。未能这样做,因为正在发送初始值,而不是我们在调用后获得的值。我希望我能够澄清我的问题
猜你喜欢
  • 1970-01-01
  • 2020-07-04
  • 2019-06-23
  • 1970-01-01
  • 2014-12-18
  • 2021-04-01
  • 1970-01-01
  • 2019-08-22
  • 2019-08-15
相关资源
最近更新 更多