我有一个 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 很好地解释了您收到此错误的原因。作为他们答案的替代方案,您可以像这样使用 count
和 url
。
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/