我试图通过向其推送新项目来更新我的状态,这是一个数组,但它一直在失败。
export interface IState{
Selected: any[]
}
export class MyComp extends React.Component<{}, IState>{
constructor(props){
super(props){
this.state = {
Selected: []
}
}
}
clickevent(newItem){
this.setState({
Selected: [...this.state.Selected, newItem]
})
OR
this.setState({
Selected: this.state.Selected.concat(newItem)
})
OR
let newArray = this.state.Selected.slice();
newArray.push(newItem)
this.setState({
Selected: newArray
})
}
}
通过更新状态将所有上述方法推送到数组中的结果
Uncaught TypeError: Cannot read property 'Selected' of null
。
答案 0 :(得分:1)
看起来您忘了绑定clickevent
。
constructor(props) {
super(props){
this.state = {
Selected: []
}
this.clickEvent = this.clickEvent.bind(this)
}
答案 1 :(得分:0)
您的状态在构造函数中初始化不正确。除此之外,您需要bind
clickEvent
函数,以便它引用正确的上下文,
constructor(props){
super(props); // Super doesn't have a function body
this.state = { // no `()` needed here since this.state is an object
Selected: []
}
this.clickEvent = this.clickEvent.bind(this);
}
检查此问题:
Uncaught TypeError: Cannot read property 'state or props' of undefined
答案 2 :(得分:0)
根据以前的状态更新状态时,应使用回调setState((prevState) => {})
方法。喜欢这个
this.setState((prevState) => ({
Selected: [ ...prevState.Selected, newItem]
}))
以下解释为什么来自docs
React可以将多个setState()调用批处理为单个更新 性能
因为this.props和this.state可以异步更新,所以 不应该依赖它们的值来计算下一个状态。