【问题标题】:ReactJS - Ajax in the sub componentReactJS - 子组件中的 Ajax
【发布时间】:2018-11-07 15:16:38
【问题描述】:

我正在使用 React + nextJS 开发一个简单的网站。

为简单起见,假设我有 2 个下拉菜单。

   Dropdown A (country)
       - Dropdown B (run time options based on the country selection)

下拉菜单 A 在主页上。 Dropdown B 是一个单独的组件。我的组件设计如下所示。

class MySubComponent extents Component{

    state = {
       options: []
    }

    static async getDerivedStateFromProps(props){
        let options = await axios(....);
        console.log(options)
        return {options};        
    }

    render(){
        <div>
           {this.state.options}
        </div>
    }


}

首页包含MySubComponent在首页

<MySubComponent loadOptionBfor={dropdownAvalue} />

Dropdown A 的 OnChange 事件应该重新加载 Dropdown B。我看到控制台日志语句显示我得到 B 的选项。但是在 ajax 请求完成之前,MySubComponent 会在没有任何选项的情况下呈现。

如何解决这个问题?

【问题讨论】:

  • getDerivedStateFromProps "应该返回一个对象来更新状态,或者 null 不更新任何东西。",它只能同步执行。我认为你最好在componentDidUpdate(prevProps) { ... } 中比较this.propsprevProps
  • @Tholle,好主意,请添加为答案

标签: javascript reactjs next.js


【解决方案1】:

getDerivedStateFromProps "should return an object to update the state, or null to update nothing",只能同步进行。

我认为你最好比较 componentDidUpdate 中的当前道具和以前的道具,如果你想比较的道具发生变化,请获取新选项。

示例

class MySubComponent extends Component {
  state = {
    options: []
  };

  async componentDidUpdate(prevProps) {
    if (prevProps.country !== this.props.country) {
      let response = await axios(/* ... */);
      this.setState({ options: response.data });
    }
  }

  render() {
    return (
      <select>
        {this.state.options.map(option => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
    );
  }
}

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 2016-10-15
    • 1970-01-01
    • 2014-04-05
    • 2018-04-20
    • 2017-03-16
    相关资源
    最近更新 更多