Javascript 使用HOC返回的组件将属性传递给组件会导致错误
我有一个Javascript 使用HOC返回的组件将属性传递给组件会导致错误,javascript,reactjs,frontend,Javascript,Reactjs,Frontend,我有一个DataComponent组件,它是一个HOC: const DataComponent = (ComposedComponent, url) => class DataComponent extends React.Component { constructor(props) { super(props); this.state = { data: [], loaded: false,
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>
);
}
}
它工作正常,然后我将count
属性传递给RandomMeUsers
,如下所示:
const RandomMeUsers = ({count}) => DataComponent(PeopleList, `https://randomuser.me/api/?results=${count}`);
ReactDOM.render(<RandomMeUsers count={10}/>, document.getElementById("app"));
const RandomMeUsers=({count})=>DataComponent(PeopleList`https://randomuser.me/api/?results=${count}`);
ReactDOM.render(,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
警告:函数作为子函数无效。
如果返回组件而不是从渲染返回组件,则可能会发生这种情况。
或者你是想调用这个函数而不是返回它。
在RandomMeUsers中
我的代码有什么问题?您已将HOC的结果转换为箭头函数。此函数不会替换组件的行为和传递道具 丑陋的语法如下所示:
const RandomMeUsers = ({ count }) => DataComponent(PeopleList, `https://randomuser.me/api/?results=${count}`);
const RandomTenUsers = RandomMeUsers({ count: 10 })
ReactDOM.render(<RandomTenUsers />, document.getElementById("app"));
@Treyco很好地解释了为什么会出现这个错误。作为他们回答的另一种选择,您可以像这样使用
count
和url
const RandomMeUsers = DataComponent(
PeopleList,
"https://randomuser.me/api/?results="
);
在你的房间里:
fetch(`${url}${this.props.count}`)
.then(response => response.json())
....
但是,如果您的
url
将来需要更多参数,则此逻辑将不太有用。因此,与其将url
作为参数传递给HOC,不如将其提取并放入props逻辑中。通过这种方式,您可以在其他地方操纵url
,并将其作为道具传递 这不是错误的原因,只是一件要避免的事情。@Emilebergron我会记住,谢谢你谢谢你的帮助和建议!感谢您的回答,但是第一个语法导致“不能将类作为函数调用”错误,第二个语法导致与我的问题相同的错误。
const RandomMeUsers = DataComponent(
PeopleList,
"https://randomuser.me/api/?results="
);
fetch(`${url}${this.props.count}`)
.then(response => response.json())
....