【问题标题】:react - onselect change display previous valuereact - onselect 改变显示以前的值
【发布时间】:2020-04-11 10:04:59
【问题描述】:

我对 React 还很陌生。

我有选择器,它返回用户选择的任何内容。

代码示例:

handleChanged(e){
    const { onSelectcountry } = this.props;
    onSelectcountry(e.target.value)
}
return (
    <div>       
        <Input type="select" name="select" value={Country} onChange={this.handleChanged.bind(this)}>
        { 
            country.map((item) => {
              return (<option value={item._id} key={item._id}> {item.name}</option>);
            })
        }
        </Input>
    </div>
);

我调度动作取决于用户选择,

import { fetchNews} from '../../actions';

    getNews(filterNews) {
        const { fetchNews } = this.props;
        fetchNews(filterNews);
    }
    onSelectcountry(country) {
        this.setState({ Country: country});
        this.getNews({
          this.state,
        })
    }

    <CountrySelector  onSelectcountry={this.onSelectcountry.bind(this)}   Country={Country}/> 

问题是:当所选值更改时,它显示了先前选择的值。

【问题讨论】:

  • 这可能是一个 setState 同步问题 - 你能通过 CodeSandbox 发布代码吗?。

标签: reactjs redux onselect


【解决方案1】:

这是由于setState 的异步特性造成的 你有一些选择:

  1. 使用setState的可选回调,更新状态后调用。
    onSelectcountry(country) {
        this.setState(
          { Country: country},
          () => this.getNews({ this.state })
        );
    }
  1. 使用手动组合的参数调用 getNews
    onSelectcountry(country) {
        this.setState({ Country: country });
        this.getNews({
          ...this.state,
          Country: country
        })
    } 
  1. componentDidUpdate回调中调用getNews,例如让 onSelectcountry 保持简单,只关心 Country 状态更新,并按预期方式处理真实状态更新。

    componentDidUpdate(prevProps, prevState){
      // coundition may vary depending on your requirements
      if (this.state.Country !== prevState.Country) {
        this.getNews(this.state);
      }
    }

    onSelectcountry(country) {
        this.setState({ Country: country});
    }

【讨论】:

  • 它工作正常,非常感谢,感谢您在各个方面的支持
猜你喜欢
  • 2012-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
相关资源
最近更新 更多