在React Native中设置状态不起作用

时间:2019-06-03 18:59:52

标签: react-native state

我正在尝试将Screen的状态设置为一些以后需要发送到数据库的值。这些值来自表格,是正确的值。现在,我遇到的问题是setState函数似乎被忽略了...

我尝试了以下代码:

handleSubmit = () => {
    const value = this._form.getValue();

    console.log(value);

    this.setState({
        description: value.description,
        places_free: value.places_free
    })
    console.log(this.state);
}

控制台的外观如下代码所示:

Struct {
  "description": "Test description",
  "phone": "09 353 90 50",
  "places_free": 2,
  "website": "http://www.oakgent.be/",
}

Object {
  "description": "",
  "latitude": 51.055979,
  "longitude": 3.711001,
  "name": "Oak Restaurant",
  "phone": "09 353 90 50",
  "places_free": null,
  "website": "http://www.oakgent.be/",
}

我还尝试通过在setState函数中自行设置变量来查看它是否与struct有关,但是得出相同的结果:

handleSubmit = () => {
    const value = this._form.getValue();

    console.log(value);

    this.setState({
        description: "test",
        places_free: 1
    })
    console.log(this.state);
}

控制台日志:

Struct {
  "description": "Test description",
  "phone": "09 353 90 50",
  "places_free": 2,
  "website": "http://www.oakgent.be/",
}

Object {
  "description": "",
  "latitude": 51.055979,
  "longitude": 3.711001,
  "name": "Oak Restaurant",
  "phone": "09 353 90 50",
  "places_free": null,
  "website": "http://www.oakgent.be/",
}

我有点卡住了,希望有人可以帮忙

2 个答案:

答案 0 :(得分:1)

setState是异步的,console.log(this.state);将返回旧数据。

  

setState()不会立即使this.state突变,而是创建一个挂起的状态转换。调用此方法后访问this.state可能会返回现有值。无法保证对setState调用的同步操作,并且可能会批量调用以提高性能。

handleSubmit = () => {
  const value = this._form.getValue();

  console.log(value);

  this.setState({
    description: "test",
    places_free: 1
  }, () => console.log(this.state))

}

演示

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      modalShow: false
    };
  }

  render() {
    return (
      <div>
        <p onClick={() => {
          console.log(this.state);
          this.setState({ modalShow: true }, () => {
            console.log(this.state);
          });
          
        }}>
          Calling state with a callback
        </p>
        <p onClick={()=> {
          console.log(this.state);
          this.setState({ modalShow: true });
          console.log(this.state);
        }}>
        Priniting state after setting value
        </p>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script>

答案 1 :(得分:1)

您需要在setState操作中控制台日志,因为setState是同步操作,因此请尝试以下操作:

this.setState({ description: "test", places_free: 1 }, () => console.log(this.state))