【发布时间】:2021-07-07 01:40:29
【问题描述】:
我正在尝试根据此页面上的作者 ID 更新帖子显示,使用 react redux 并在其他两个组件中使用 useCallBack 来更新计数和 authorID,但下面的子项没有更新。
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 dev tools中,authorID状态变为选中的数字,只有在post.js中没有更新。
我是 react 和 redux 的新手,任何帮助都会非常感谢!
【问题讨论】: