在React中获取和更新数据的最佳方法

时间:2019-01-02 12:34:38

标签: javascript reactjs react-native

关于获取和更新数据,我有几个问题。 例如,如果我收到的帖子数量很大,并且我使用组件级别状态进行处理。 我使用两种方法,第一种是在componentDidMount内调用api并相应地更新状态

 componentDidMount() {
        this.getData();
  // get data handles all the state changes etc etc 
 }

但是使用这种方法,如果我有多个api和状态更改,它将导致组件混乱。 为了解决该问题,我尝试了使用HOC进行数据提取。

例如

const AppWithFetch = withFetching('www.getsomething.com/posts')(MyComponent);

在这里,我的hoc会收到一个URL,并相应地将数据作为道具。 hoc将这些变量作为我组件的道具 --data(最初为null) --isLoading(最初为true) --error(最初为false) 并且在我的组件内部,那么我不需要componentDidMount和其他逻辑,我只需要通过检查this.props.isLoading来进行一些条件渲染。 这看起来很完美。但是,我还有另一个问题,我无法有效解决。假设我获取了数据,现在在组件内部进行操作或导致数据更改的操作,因为作为道具收到的数据无法更改。 换句话说,我想将我的视图和api逻辑分开(包括获取和更新)。 我希望有一些好的建议。 谢谢

我现在临时提取

 const withFetching = (url) => (Component) =>
    class WithFetching extends React.Component {
        constructor(props) {
            super(props);

            this.state = {
                data: null,
                isLoading: false,
                error: {
                    error: false,
                    message: null
                },
            };
        }

        async componentDidMount() {
            this.setState({ isLoading: true });
            const token = await AsyncStorage.getItem('userToken');
            try {
                const { data } = await axios({
                    method: 'get', //you can set what request you want to be
                    url: `${SERVER_URL}${url}`,
                    headers: {
                        'x-auth-Token': token
                    }
                });
                if (validateData(data)) {
                    if (data.status == 'OK') {
                        return this.setState({
                            data: data.data, isLoading: false
                        });
                    }
                    this.setState({
                        error: {
                            error: true,
                            message: data.message
                        },
                        isLoading: false
                    });
                } else {
                    this.error({
                        error: {
                            error: true,
                            message: errorResponse.message
                        },
                        isLoading: false

                    });
                }
            } catch (e) {
                this.error({
                    error: errorResponse.message, isLoading: false
                });
            }
        }

        render() {
            return <Component {...this.props} {...this.state} />;
        }
    };
export default withFetching;

0 个答案:

没有答案
相关问题