javascript - 使用 HOC 返回的组件将属性传递给组件会导致错误

标签 javascript reactjs frontend

我有一个 DataComponent 组件,它是一个 HOC:

const DataComponent = (ComposedComponent, url) => 
class DataComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            loaded: false,
            loading: false
        };
    }

    componentWillMount() {
        this.setState({loading: true});
        fetch(url)
            .then(response => response.json())
            .then(data => this.setState({
                data,
                loading: false,
                loaded: true
            }));
    }

    render() {
        return(
            <div className="data-component">
                {(this.state.loading) ? 
                    <div>Loading</div> :
                    <ComposedComponent {...this.state}/>}
            </div>
        );
    }
}

然后我使用 RandomMeUsers 渲染该 HOC(PeopleList 是另一个组件):

const RandomMeUsers = DataComponent(PeopleList, `https://randomuser.me/api/?results=10`);

ReactDOM.render(<RandomMeUsers/>, document.getElementById("app"));

它工作正常,然后我将 count 属性传递给 RandomMeUsers,如下所示:

const RandomMeUsers = ({count}) => DataComponent(PeopleList, `https://randomuser.me/api/?results=${count}`);

ReactDOM.render(<RandomMeUsers count={10}/>, document.getElementById("app"));

当我运行它时,浏览器向我发送以下错误:

Warning: Functions are not valid as a React child. 
This may happen if you return a Component instead of  from render. 
Or maybe you meant to call this function rather than return it.
in RandomMeUsers

我的代码有什么问题?

最佳答案

@Treyco 很好地解释了您收到此错误的原因。作为他们答案的替代方案,您可以像这样使用 counturl

const RandomMeUsers = DataComponent(
  PeopleList,
  "https://randomuser.me/api/?results="
);

在你的 HOC 内部:

fetch(`${url}${this.props.count}`)
    .then(response => response.json())
    ....

但是如果您的 url 将来需要更多参数,此逻辑将不太有用。因此,您可以提取它并将其放入 props 逻辑中,而不是将 url 作为参数传递给 HOC。通过这种方式,您可以在其他地方操作您的 url 并将其作为 prop 传递。

关于javascript - 使用 HOC 返回的组件将属性传递给组件会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54076460/

相关文章:

javascript - Reactjs:更新特定行

html - CS-CART后台是否使用960.gs? (多供应商 v4.2.4)

javascript - 找不到 'source-map' 的类型定义文件

javascript - 前端JavaScript加载 View 的设计模式

javascript - 每 60 秒仅启动一次事件 (JavaScript)

javascript - 为什么 substring 方法会以这种方式运行?

reactjs - 在 React Router Dom 中实现后退导航的问题

reactjs - 如何在 MUI 数据网格中的 renderCell 组件之间传递状态

javascript - 如何使用react js将html表单提交的信息显示到另一个页面上?

javascript - 如何在 this.state 中使用 this.state