javascript - 即使在 this.setState({query :value}) call

标签 javascript reactjs

我有一个组件,其中包含用户在文本框中插入内容时的处理程序函数。完成后,query状态对象中的字段应设置为文本框的值。

例如,如果文本框为空,然后用户输入“s”,则handleInput()中,我会做this.setState({event.target.value}) ,应设置 this.state.query到“s”。但这行不通。

当我输入“s”时,行 alert("setting query to "+this.state.query);显示我 "setting query to" ,而不是预期的 "setting query to s" 。这对我来说真的很奇怪,因为 alert(event.target.value) 行打印出“s”,所以该值肯定在 event.target.value 中。

然后,如果我输入另一个字符,例如“a”,警报会显示“将查询设置为 s”。就好像this.state.query一直落后1个字符。代码如下:

class Search extends Component {
  constructor(props){
    super(props);
    let today = new Date();
    this.state = {
      searchSuggestion: 'Search for tweets here',
      anchorEl: null,
      date: today.toJSON(),
      geocode: undefined,
      page: 0,
      placeName: 'the World',
      query: ''
    }
    // Defining debounce is needed in constructor 
    this.searchTweets = debounce(500, this.searchTweets);
    this.searchGeocode = debounce(500, this.searchGeocode);
  }

  componentDidMount() {
    modelInstance.addObserver(this);
  }

  handleInput = event => {
    alert("Handling input");
    let query = event.target.value;
    alert(event.target.value); // "s"
    this.setState({
      query: event.target.value
    });
    alert("setting query to "+this.state.query); // outputs "setting query to". this.state.query isn't set to anything!
    let until = new Date(this.state.date);
    this.searchTweets(query, this.state.geocode, until);
  }

  // Searches tweets until date
  searchTweets = (query, location, date) => {
    this.props.handleStatusChange('INITIAL');
    modelInstance.searchTweets(query, location, date).then(result => {
      modelInstance.setTweets(result);
      this.props.handleStatusChange('LOADED');
      this.setState({
        data: result
      });
    }).catch(() => {
      this.props.handleStatusChange('ERROR');
    });
  }

  render(){
    return(
        <div className='search'>
          <Row id='searchInput'>
            <SearchInput handleInput={this.handleInput.bind(this)} searchInput={this.state.searchInput} searchSuggestion={this.state.searchSuggestion} page={1}/>
          </Row>
          <Row>
            <SearchNav page={this.state.page}/>
          </Row>
          <Row id='date-location'>
            <Col xs={2} sm={2} md={2} className='text'>
              <p>UNTIL</p>
            </Col>
            <Col xs={4} sm={4} md={4} className='date'>
              <SearchDate date={this.state.date} anchorEl={this.state.anchorEl} click={this.handleClick} dayChange={this.onDayChange}/>
            </Col>
            <Col xs={2} sm={2} md={2} className='text'>
              <p>IN</p>
            </Col>
            <Col xs={4} sm={4} md={4} className='location'>
              <SearchLocation placeName = {this.state.placeName} handleLocation={this.handleLocation.bind(this)}/>
            </Col>

          </Row>
        </div>
    )
  }
}

export default Search;

怎么会出现这种情况?

最佳答案

发生这种情况是因为 state updates are asynchronous :

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

它说this.propsthis.state可能异步更新”但它应该几乎说是,更新目前始终是异步的,它只是可能会也可能不会批处理。

如果您需要在更新 this.state 后执行某些操作,请使用 second argument ,这是更新时的回调。

关于javascript - 即使在 this.setState({query :value}) call,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50086851/

相关文章:

javascript - 在 JavaScript 中,如何创建带有可选参数的函数?

javascript - 链接到 Next.js 中的动态路由

node.js - intellij Idea 不断安装类型包

javascript - 有没有办法让父Link排除一些子元素?

reactjs - 使用 TS 使用 react-hook-form 构建应用程序时出错

reactjs - Antd中如何获取form.item中Upload的值?

javascript - 防止父 div 在子 div 调整大小时调整大小

javascript - react native "is not a function"

java - 股票行情有问题

javascript - 如何在javascript中使用多个按钮来实现相同的功能?