简体   繁体   English

父 state 更改后子组件未更新。反应

[英]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.我正在尝试根据此页面上的作者 ID 更新帖子显示,使用 react redux 并在其他两个组件中使用 useCallBack 来更新计数和 authorID,但下面的孩子没有更新。

Post.js 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应用程序.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 .当 authorID 更改为 5 或 10 时,console.log 和按钮仍会为the.state.authorID显示 1。 (the number should change when I click the button), but still says 1, (当我单击按钮时,数字应该会改变),但仍然是 1,

the methods: componentDidUpdate() and componentWillReceiveProps(nextProps) did not run.方法: componentDidUpdate()componentWillReceiveProps(nextProps)没有运行。

In redux dev tools, the authorID state changes to the number selected, only in the post.js is not updating.在 redux 开发工具中,authorID state 更改为所选数字,仅在 post.js 中不更新。

I am pretty new to react and redux, any help would be great thanks!我对反应和 redux 很陌生,任何帮助都会非常感谢!

For one, React components should never directly reference store as you did as they will not rerender on store change that way.一方面,React 组件永远不应该像您那样直接引用store ,因为它们不会以这种方式在 store 更改时重新呈现。

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.此外, 您不应该将道具复制到本地组件 state中,因为如果您不编写额外的逻辑,这些道具通常不会更新 - 而且该逻辑经常会导致错误。 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 ).或者在子组件中进行自己的useSelector调用(假设您将其编写为 function 组件,在大多数情况下它是可取的并且更具前瞻性。如果您坚持使用 class 组件,您将需要使用connect ,处理起来更复杂比useSelector )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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