【发布时间】:2022-01-11 17:05:25
【问题描述】:
我正在获取数据(一个对象)到一个 redux 状态,并将这个对象放入一个 react prop。
如果在单击按钮时检索数据,则代码工作正常。但是我想在渲染不起作用的组件时检索数据。相反,我收到错误 Cannot read properties of undefined (reading 'id')
这段代码确实有效,我可以看到检索到的对象处于 redux 状态(在 Chrome redux-devtool 中):
export class Main extends Component {
componentDidMount(){
this.props.getQuery();
}
onClick = () => {
console.log(this.props.query.query.id)
}
render() {
return (
<div>
<Button onClick={this.onClick}>Print id</Button>
</div>
)
}
}
const mapStateToProps = state => ({
query: state.query.query
});
export default connect(mapStateToProps, { getQuery })(Main)
但是这段代码不起作用:
export class Main extends Component {
componentDidMount(){
this.props.getQuery();
console.log(this.props.query.query.id) //This line throws an error
}
onClick = () => {
console.log(this.props.query.query.id)
}
render() {
return (
<div>
<Button onClick={this.onClick}>Print id</Button>
<p>this.props.query.query.id</p> //This line throws an error
</div>
)
}
}
const mapStateToProps = state => ({
query: state.query.query
});
export default connect(mapStateToProps, { getQuery })(Main)
我是 react 和 redux 的新手,因此非常感谢任何帮助。 谢谢!
【问题讨论】: