简体   繁体   中英

Child Component not updating after parent state changes.React

I am trying to update posts display based off authors ID on this page, using react redux and using useCallBack in the other two components to update the count and authorID, but the child below is not updating.

Post.js

import React from 'react'
import '../App.css';
import axios from 'axios'
import { Button } from '@material-ui/core';

class Posts extends React.Component {
    constructor(props){
        super(props);
        this.state = {
          authorID: this.props.authorID,

        }
        console.log(this.state)
        this.handlePosts = this.handlePosts.bind(this);
        this.handleCardPosts = this.handleCardPosts.bind(this);
      }
     
      componentDidMount() {
        console.log("mount")
        this.render();
      }

      componentDidUpdate() {
        console.log("updated")
        this.render();
      }

      componentWillReceiveProps(nextProps) {
        this.setState({ authorID: nextProps.authorID });  
        console.log(`prop update pls`)
        console.log(this.state.authorID);
      }

      shouldComponentUpdate(){
        console.log(this.state)
        if(this.state.count !== this.props.count){
          return true;
        } else { 
          return false
        }
      }

      async handlePosts(){
        const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${this.state.authorID}/posts`)
        const posts = response.data;
        console.log(this.state.authorID)
        console.log(posts)
      }

      handleButton(){
        return (
          <div>
              <Button className="showButton" variant="outlined" color="primary" onClick={this.handlePosts}>
                 {this.state.authorID}
              </Button>
          </div>
        )
      }

      render(){
        return this.handleButton()
      }

}

export default Posts;

// parent component

App.js


function App() {
  const classes = useStyles();
  const getAuthor = store.getState().authorReducer.authorID;
  const getCount = store.getState().countReducer.count;
  
  const updateAuthor = (value) => {
    store.dispatch(setAuthor(value))
  }
  
  const updateCount = (value) => {
    store.dispatch(setCount(value))
  }


  return (
    
    <Provider store={store}>
      <Grid container spacing={1} className={classes.container}>
        <Grid item xs={12} sm={6}>
            <Authors authorID={getAuthor} onAuthorChange={updateAuthor}/>
        </Grid>
        <Grid item xs={12} sm={6}>
            <Counts count={getAuthor} onCountChange={updateCount}/>
        </Grid>
        <Grid item xs={12}>
            <Posts authorID={getAuthor} count={getCount} />
        </Grid>
      </Grid>
    </Provider>
  );

When authorID changes to a 5 or 10 the console.log and button still shows 1 for the.state.authorID . (the number should change when I click the button), but still says 1,

the methods: componentDidUpdate() and componentWillReceiveProps(nextProps) did not run.

In redux dev tools, the authorID state changes to the number selected, only in the post.js is not updating.

I am pretty new to react and redux, any help would be great thanks!

For one, React components should never directly reference store as you did as they will not rerender on store change that way.

So, instead write it like this:

  const author = useSelector(store => store.authorReducer.authorID);
  ...

  const dispatch = useDispatch()
  const updateAuthor = (value) => {
    dispatch(setAuthor(value))
  }

Also, you should not copy props into local component state , as those usually will not update without you writing additional logic - and that logic very often leads to bugs. So just reference your props. Or make your own useSelector call in the child component (assuming you write that as a function component which in most cases is preferrable and more futureproof. If you stick with a class component, you will need to use connect , which is more complex to handle than useSelector ).

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