React 错误 Cannot read property ‘props’ of undefined 修复
“Cannot read property ‘props’ of undefined”错误发生在没有将正确上下文绑定到 this 关键字的情况下调用类方法。 要解决该错误,请将类方法定义为箭头函数或在类的构造方法中使用 bind 方法。
如果在功能组件中遇到错误,请向下滚动到下一部分。
下面是错误发生方式的示例。
import React, {Component} from 'react';
class App extends Component {
logProps() {
// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'props')
console.log(this.props);
}
render() {
return (
<div>
<button onClick={this.logProps}>Log props</button>
</div>
);
}
}
export default App;
请注意,我们定义了 logProps
方法,但我们没有绑定 this 关键字的上下文。因此,logProps 方法中的 this 关键字的值为 undefined。
要解决该错误,需要将 logProps 方法切换为使用箭头函数。
import React, {Component} from 'react';
class App extends Component {
// ?️ 现在使用 箭头 函数
logProps = () => {
console.log(this.props);
};
render() {
return (
<div>
<button onClick={this.logProps}>Log props</button>
</div>
);
}
}
export default App;
这是有效的,因为箭头函数使用封闭范围的 this 关键字——在我们的示例中,封闭范围是特定的组件实例。
如果功能组件中收到“Cannot read property ‘props’ of undefined”错误,请确保没有使用 this 关键字访问 props,例如 使用 props.myProp
而不是 this.props.myProp
。
function Button(props) {
return (
<button onClick={() => console.log('button clicked')}>
{props.text}
</button>
);
}
function App() {
return (
<div>
<Button text="Click" />
</div>
);
}
export default App;
请注意,Button 组件使用 props.text 来访问传递给它的 text 属性。
或者,我们可以解构 prop 以不必在 props 对象上访问它。
function Button({text}) {
return (
<button onClick={() => console.log('button clicked')}>
{text}
</button>
)
}
function App() {
return (
<div>
<Button text="Click" />
</div>
);
}
export default App;
我们从 props 对象中解构了 text 属性,因此 Button 组件现在可以直接访问它。
我们可以根据需要对尽可能多的道具执行此操作。
function Button({text, disabled}) {
return (
<button disabled={disabled} onClick={() => console.log('button clicked')}>
{text}
</button>
);
}
function App() {
return (
<div>
<Button text="Click" disabled={false} />
</div>
);
}
export default App;
效果如下
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。