让我说一个这样的状态:
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1'
}
}
}
然后我setState
FirstTime
添加另一个键/值:
this.setState({FirstTime: {...this.state.FirstTime, bar: 'ex2'}})
有一种方法可以将初始状态更改为这样:
constructor(props) {
super(props);
this.state = {
FirstTime:
{
foo: 'ex1',
bar: 'ex2'
}
}
}
我何时重新加载应用程序?
答案 0 :(得分:1)
尝试这样的事情
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
FirstTime: {
foo: 'ex1'
}
}
}
render() {
console.log(this.state.FirstTime); //Sorry a typo found in this line
return (
<div>Hey</div>
);
}
componentDidMount() {
let obj = {
bar: 'ex2'
}
let finalData = { ...this.state.FirstTime, ...obj }
this.setState({ FirstTime: finalData })
}
}
const rootElement = document.getElementById("root")
ReactDOM.render(
<App />,
rootElement
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>