简体   繁体   中英

React - Call setState in parent when child is called

I am building a blog in react where I get the data from a JSON-API and render it dynamically. I call setState in my app.js to get the data from JSON via axios and route with match.params to the post pages(childs). This works fine, BUT if I call the child (URL: ../blog/post1) in a seperate window it doesnt get rendered. It works if I hardcode the state.

So, I see the issue, what would be the best way to fix it?

Parent:

class App extends Component {
  constructor(props) {
    super();
    this.state = {
      posts: []
    }

getPosts() {
  axios.get('APIURL')
  .then(res => {
    let data = res.data.posts;
    this.setState({
      posts: data
    })
  })
}

componentDidMount = () => this.getPosts()

Child:

UPDATE - Found the error: The component threw an error, because the props were empty. This was because the axios getData took some time.

Solution: I added a ternary operator to check if axios is done and displayed a css-spinner while loading. So no error in component.

Dynamic Routing works like a charme.

You can do this with binding . You would need to write a function like

setPosts(posts) {
  this.setState({posts});
}

in the parent, and then in the parent, bind it in the constructor , like so.

this.setPosts = this.setPosts.bind(this);

When you do this, you're attaching setPosts to the scope of the parent, so that all mentions of this in the function refer to the parent's this instead of the child's this . Then all you need to do is pass the function down to the child in the render

<Child setPosts={this.setPosts} />

and access that method in the child with

this.props.setPosts( /*post array goes here */ );

This can apply to your getPosts method as well, binding it to the parent class and passing it down to the Child.

When you hit the /blog/post1 url, it renders only that page. The App component is not loaded. If you navigate from the App page, all the loading has been done and you have the post data in the state of the child component.

Please refer to this SO question . This should answer your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM