React Native-我可以设置动态初始状态吗?

时间:2018-07-22 10:01:00

标签: react-native

让我说一个这样的状态:

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'
    }
  }
}

我何时重新加载应用程序?

1 个答案:

答案 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>