父状态更改后子组件不会更新。反应

时间:2021-04-11 21:51:06

标签: reactjs redux state

我正在尝试根据此页面上的作者 ID 更新帖子显示,在其他两个组件中使用 react redux 和 useCallBack 来更新计数和作者 ID,但下面的子项未更新。

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;

// 父组件

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>
  );

当 authorID 更改为 5 或 10 时,console.log 和按钮仍然为 the.state.authorID 显示 1。 (当我点击按钮时数字应该改变),但仍然显示 1,

方法: componentDidUpdate() componentWillReceiveProps(nextProps) 没有运行。

在 redux 开发工具中,authorID 状态变为选中的数字,只有在 post.js 中没有更新。

我对 react 和 redux 还很陌生,任何帮助都会非常感谢!

1 个答案:

答案 0 :(得分:1)

一方面,React 组件不应该像您那样直接引用 store,因为它们不会以这种方式重新呈现存储更改。

所以,改为这样写:

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

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

另外,you should not copy props into local component state,因为如果您不编写额外的逻辑,那些通常不会更新 - 并且该逻辑经常会导致错误。 所以只需参考你的道具。或者在子组件中进行自己的 useSelector 调用(假设您将其编写为函数组件,这在大多数情况下更可取且更具前瞻性。如果您坚持使用类组件,则需要使用 {{1} },它比connect更复杂。