简体   繁体   English

在反应中更改高阶组件中的道具

[英]Change props in Higher-Order-Component in react

I am trying to understand higher-order-components(referred to as HOC below):我试图理解高阶组件(以下称为 HOC):

As such, I have created a sample HOC to do GET requests for my component:因此,我创建了一个示例 HOC 来为我的组件执行 GET 请求:

import React from 'react';
import { Text } from 'react-native';
import axios from 'axios';

export default (Elem,  props = {}) => {
    // mock props for testing
    props = {
        apiRequests: {
            "todoList": {
                url: "https://jsonplaceholder.typicode.com/todos"
            }
        }
    }
    return class extends React.Component {
        componentWillMount() {
            let apis = Object.keys(props.apiRequests);
            for(let i = 0; i < apis.length; i++) {
                props.apiRequests[apis[i]].done = false
                axios.get(props.apiRequests[apis[i]].url).then((resp) => {
                    console.warn("done")
                    props.apiRequests[apis[i]].done = true
                    props.apiRequests[apis[i]].data = resp.data
                })
            }
        }

        render() {
            return (<Elem {...props} />)
        }
    }
}

Now, when I wrap my component with the above HOC, I get the props with done as false .现在,当我用上面的 HOC 包装我的组件时,我得到了donefalse的道具。

However, soon, when I get my API response, the HOC logs done in my console, but the data in my component isn't updated.但是,很快,当我收到 API 响应时,HOC 会在我的控制台中记录done ,但我的组件中的数据没有更新。 What am I doing wrong?我究竟做错了什么?

Props are immutable.道具是不可变的。 This这个

props.apiRequests[apis[i]].done = true

is a mistake and won't cause child component to be re-rendered.是一个错误,不会导致子组件被重新渲染。

A state that is received from asynchronous request should be stored in component state, setState triggers a re-render.从异步请求接收到的状态应该存储在组件状态中, setState会触发重新渲染。 componentWillMount was deprecated because it was misused for asynchronous routines. componentWillMount已被弃用,因为它被误用于异步例程。 It should be:它应该是:

return class extends React.Component {
    this.state = {};

    componentDidMount() {
        let apis = Object.keys(props.apiRequests);
        for(let i = 0; i < apis.length; i++) {
            axios.get(props.apiRequests[apis[i]].url).then((resp) => {
                this.setState({ apis[i]]: resp.data });
            })
        }
    }

    render() {
        return (<Elem data={this.state} />)
    }
}

Depending on how data is expected to be received, state updates could be performed in batch with Promise.all .根据预期接收数据的方式,可以使用Promise.all批量执行状态更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM