gpt4 book ai didi

javascript - 如何从传递给 react 组件的 Prop 设置状态?

转载 作者:搜寻专家 更新时间:2023-11-01 05:28:26 27 4
gpt4 key购买 nike

我有这个简单的组件,initialPlayers 属性被传递给 App 组件。

import React from 'react';
import ReactDOM from 'react-dom';

var PLAYERS = [
{
name: "xyz",
score: 123
}
];

// App component
class App extends React.Component {

constructor() {
super();
}

componentDidMount() {
this.state = {
players: this.props.initialPlayers
}
}

render() {
return(
<div>
<Header players={this.state.players} />
</div>
);
}
}

// Render component
ReactDOM.render(<App initialPlayers={ PLAYERS }/>,
document.getElementById('root'));

在控制台中出现此错误,并且无法将值作为 {this.state.players} 传递给 Header 组件。有什么想法吗?

Uncaught TypeError: Cannot read property 'players' of null
at App.render (bundle.js:14379)
at bundle.js:20173
at measureLifeCyclePerf (bundle.js:19452)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (bundle.js:20172)
at ReactCompositeComponentWrapper._renderValidatedComponent (bundle.js:20199)
at ReactCompositeComponentWrapper.performInitialMount (bundle.js:19739)
at ReactCompositeComponentWrapper.mountComponent (bundle.js:19635)
at Object.mountComponent (bundle.js:4667)
at ReactCompositeComponentWrapper.performInitialMount (bundle.js:19748)
at ReactCompositeComponentWrapper.mountComponent (bundle.js:19635)

最佳答案

将设置玩家行移动到您的构造函数()中:

constructor(props) {
super(props);
this.state = {
players: this.props.initialPlayers
};
}

关于javascript - 如何从传递给 react 组件的 Prop 设置状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43621003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com