setState之后组件不会重新呈现

时间:2018-08-17 11:32:00

标签: javascript reactjs

我最近开始使用React,想要构建一个小应用程序来获取天气数据。我的API具有返回自动完成建议的功能。因此,当我的自动提示数组不为空时,我呈现一个列表,然后单击<li>'s中的一个,我希望该值在输入框中。我设法设置了SearchBar的状态,但是无法更改其值。

修改:我尝试将自己的价值从changeState()转移到<input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} />中。我可以搜索其他术语。

import React from 'react';
import './SearchBar.css';
import Suggestion from './Suggestion';

class SearchBar extends React.Component{
  constructor(props) {
    super(props);
    this.state = {inputValue: ''};
    this.search = this.search.bind(this);
    this.updateInputValue = this.updateInputValue.bind(this);
    this.handleKeyPress = this.handleKeyPress.bind(this);
    this.changeState = this.changeState.bind(this);
  }

  changeState(value) {
    console.log(value);
    // Logs value of text between <li></li>
    this.setState({inputValue: value});
  }

  search() {
    this.props.onSearch(this.state.inputValue);
  }

  updateInputValue(evt) {
    this.setState({
      inputValue: evt.target.value
    });
    this.props.onChange(this.state.inputValue);
  }

  handleKeyPress(e) {
    if(e.key === 'Enter') {
      this.search();
    }
  }

  render() {
    return (
      <div>
        <div className="SearchGroup" onKeyPress={this.handleKeyPress} >
          <input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} />
          <a onClick={this.search}>Go</a>
        </div>
        <Suggestion autocomplete={this.props.autocomplete} onSelect={this.changeState} />
      </div>
    );
  }
}

export default SearchBar;

为了完整起见,我的Suggestion.js

import React from 'react';
import './Suggestion.css';

class Suggestion extends React.Component{
  constructor(props) {
    super(props);
    this.updateInputField = this.updateInputField.bind(this);
  }

  updateInputField(evt) {
    this.props.onSelect(evt.currentTarget.innerText);
  }

  render(){
      if(this.props.autocomplete && this.props.autocomplete.length > 0) {
        return (
          <div className="Suggestion">
            <ul>
              {
                this.props.autocomplete.map((location) => {
                  return (
                    <li key={location.id} onClick={this.updateInputField}>{location.name}</li>
                  )
                })
              }
            </ul>
          </div>
        );
      } else {
        return <div className="None"></div>
      }
  }
}

export default Suggestion;

我也希望在location.url中提交Suggestion,但找不到与evt内部匹配的属性。

3 个答案:

答案 0 :(得分:1)

如我的评论中所述。您正在设置状态,并立即将状态传递给updateInputValue事件处理函数中的onChange函数,这是不正确的。由于您不会立即更新状态值,因此状态值仅在呈现时才更新,因此请像下面一样直接传递evt.target.value

s = df['Main'].fillna('').str.strip('[]').str.split(';|\]\s+\[')

要在输入字段中查看更改的值,您必须将value属性传递给以下输入标签

updateInputValue(evt) { 
   this.setState({ inputValue: evt.target.value }); 
   this.props.onChange(evt.target.value);
}

答案 1 :(得分:0)

我猜您正在尝试使用尚未存在的状态中的值,因为setState是异步的 所以可以在setState上使用回调

updateInputValue(evt) {
  this.setState({
    inputValue: evt.target.value
  }, ()=> this.props.onChange(this.state.inputValue));
}

或者直接使用event中的值

updateInputValue(evt) {
  const value = evt.target.value
  this.setState({
    inputValue: value
  });
  this.props.onChange(value)
}

加上您尚未将值分配回您的输入:

<input type="text" placeholder="City, Zip Code, Coordinates" onChange={evt => this.updateInputValue(evt)} value={this.state.inputValue}/>

答案 2 :(得分:0)

React setState不会立即更新状态。它将其放入队列并批量更新状态。如果要访问更新的状态,请在setState callBack

中编写代码
this.setState({ inputValue: evt.target.value},()=> this.props.onChange(this.state.inputValue));

类似的东西

相关问题