【问题标题】:React Component - reload data within multiple timesReact Component - 多次重新加载数据
【发布时间】:2019-03-27 20:51:44
【问题描述】:

想象一个带有<select> 元素的简单 React 组件,它允许根据国家/地区选择城市。例如

<MyCitySelectComponent
  country={ 'France' }
  city={ 'Paris' }
  onChange={ someFunction }
/>
  • 安装后,它应加载可用城市列表(基于国家/地区)并呈现&lt;select&gt;
  • 当 city 属性改变时 - 它应该修改 &lt;select&gt; 输入值并触发 onChange 事件。
  • 当 country 属性发生更改(从父组件) - 它应该从远程服务器重新加载可用城市列表并触发相同的 onChange 事件。

我设法实现了前两个,这里是简化的代码:


class MyCitySelectComponent extends Component {
    constructor(props) {
        super(...props);

        this.state = {
            cities: null,
            city: props.city,
            country: props.country
        };
    }

    onCityChange( e ) {
        this.setState({
            city: e.target.value
        });

        this.props.onChange( e.target.value );
    }

    loadCities() {
        fetch({
            path: '/get/cities?country=' + this.state.country,
        }).then( cities => {
            this.setState({
                cities: cities
            });
        });
    }

    componentDidMount() {
        this.loadCities();
    }

    render() {
        if ( !this.state.cities ) {
            // not loaded yet
            return null;
        }

        return (
            <select>
                { this.state.cities.map( ( name, index ) =>
                    <option
                        value={ name }
                        onChange={ this.onCityChange }
                        selected={ name === this.state.city }
                    />
                ) }
            </select>
        )
    }
}

但是当从父组件动态更改国家/地区时,我无法重新加载城市。我尝试使用shouldComponentUpdate,但我得到的只是无限循环。

这种类型的组件有什么模式吗?

谢谢。

【问题讨论】:

标签: javascript reactjs ecmascript-6


【解决方案1】:

应在componentDidUpdategetDerivedStateFromProps 中处理基于prop 更改的新数据。查看文档以获取示例:https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change

请注意,componentWillReceiveProps 已弃用!

【讨论】:

    猜你喜欢
    • 2016-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    相关资源
    最近更新 更多