我找不到關于這種情況的任何資訊,我正在將p1道具從我的 App 組件傳遞到我的 Child1 組件的狀態。
當我呼叫buttonHandler方法查看 s1 的狀態時,我收到此錯誤:
Child1.js:27 Uncaught TypeError: Cannot read properties of undefined (reading 'state')
類組件“Child1”
import React from "react";
import { setState } from 'react'
class Child1 extends React.Component {
constructor(props) {
super(props)
this.s2 = 0
this.state = {
s1: this.props.p1
}
console.log(this.state.s1);
}
componentDidMount() {
// console.log('componentDidMount()')
console.log('s2 = ' this.s2);
this.s2 = 1
this.setState(() => ({
s1: this.props.p1 1
}))
}
buttonHandler() {
console.log(this.state.s1);
}
render() {
return (
<>
<div>
<h3>State s1</h3>
<h4>{this.state.s1}</h4>
</div>
<hr />
<div>
<h3>props from p1 to s2</h3>
<h4>{this.s2}</h4>
</div>
<hr />
<div>
<button onClick={this.buttonHandler}>Push</button>
</div>
</>
)
}
}
export default Child1
應用程式.js
import './App.css';
import Child1 from './Child1';
function App() {
return (
<>
<Child1 p1={88} />
</>
)
}
export default App;
uj5u.com熱心網友回復:
使用類實體,您需要將函式系結到組件實體:
// Use arrow syntax (recommended) or bind in the constructor
buttonHandler = () => {
console.log(this.state.s1);
};
uj5u.com熱心網友回復:
上面的代碼有3個問題:
- 事件監聽方法系結(在
buttonHandler方法中) - 使用道具初始化狀??態(在建構式中)
setState在(incomponentDidMount)中使用 prop 值
對于事件偵聽器系結,如 Dennis Valsh 的回答所示:
buttonHandler = () => {
console.log(this.state.s1);
};
要使用道具初始化狀??態,最好使用getDerivedStateFromProps.
static getDerivedStateFromProps(props, state) {
return {s1: props.p1 1};
}
要使用 props 更新狀態,請使用setState. (見https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)
setState((state,props) =>{
return {s1: props.p1 1};
}
但是,由于您要執行的操作不是很清楚,因此我會說您根本不需要,componentDidUpdate并且getDerivedStateFromProps就足夠了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/491311.html
標籤:javascript 反应
