[英]Props are not passed with React.cloneElement in the render() method
我有两个反应组件,一个Layout
类和一个HomePage
类:
HomePage
是一个需要有products
道具的组件。
主页.js
import React, { Component } from 'react';
export class HomePage extends Component {
render() {
if (!this.props.products) {
return (<div>Products not loaded yet</div>);
}
return (<div>Products loaded!</div>);
}
}
Layout
是一个组件,用于显示来自react-router
建立react-router
。 这个类负责使用React.cloneElement
将products
道具传递给孩子
布局.js
import React, { Component } from 'react';
import { NavMenu } from './NavMenu';
import { Footer } from './Footer';
export class Layout extends Component {
constructor(props) {
super(props);
this.state = {
products: null,
loading: true
};
}
// Make an api call when the component is mounted in order to pass
// additional props to the children
componentDidMount() {
this.populateProductsData();
}
async populateProductsData() {
const response = await fetch('api/products/all');
const data = await response.json();
this.setState({ products: data, loading: false });
}
render() {
if (this.state.loading) {
return (<div>App loading</div>);
}
const childrenWithProps = React.Children.map(this.props.children, child => {
const props = { products: this.state.products };
if (React.isValidElement(child)) {
return React.cloneElement(child, props);
}
return child;
});
return (
<div>
<NavMenu />
{childrenWithProps}
<Footer />
</div>
);
}
}
路由是在App
组件中进行的:
应用程序.js
export default class App extends Component {
render () {
return (
<Layout>
<Route exact path='/'
component={HomePage}/>
</Layout>
);
}
因此,我期待
App loading
消息的页面Layout
子项时,有一个包含Products not loaded yet
的Products not loaded yet
消息的Layout
Products loaded!
了Products loaded!
的页面Products loaded!
信息但是,应用程序停留在第二步:子组件永远不会收到products
属性。 代码编译通过,没有运行时错误,后端 Api 被触发并发送有效响应。
为什么product
道具永远不会在子HomePage
组件的render()
方法中可用?
按照@Nikita Chayka 的回答,应该在路由时传递道具:
布局.js
export class Layout extends Component {
render() {
return (
<div>
<NavMenu />
{this.props.children}
<Footer />
</div>
);
}
}
应用程序.js
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
products: null,
loading: true
};
}
componentDidMount() {
this.populateProductsData();
}
async populateProductsData() {
const response = await fetch('/api/products/all');
const data = await response.json();
this.setState({ products: data, loading: false });
}
render() {
if (this.state.loading)
return (<div>App loading</div>);
return (
<Layout>
<Route exact path='/'
render={(props) => (<HomePage {...props} products={this.state.products}/>)}/>
</Layout>
);
}
}
您的 Layout 组件会将 products 属性传递给 Route 组件,而不是 Home 组件,基本上您将拥有
<Route products={} component={Home} path="/" exact/>
但是你需要把它传递给 Home,你可以在这里检查想法 - https://ui.dev/react-router-v4-pass-props-to-components/
编辑
您不应向 Route 提供组件属性,而应仅提供渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.