[英]Passing an object as prop in React-Router Route
I'm trying to pass object props to Payments component using render method in route.我正在尝试在路由中使用渲染方法将 object 道具传递给付款组件。
I have tried pass props to the functional components, but still no luck.我已经尝试将道具传递给功能组件,但仍然没有成功。
App.js应用程序.js
class App extends Component {
state = {
user: {},
};
componentDidMount() {
const url = "/api/current-user";
fetch(url, {
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
credentials: "same-origin",
method: "GET",
})
.then((response) => {
if (!response.ok) {
return response.json().then((err) => {
throw err;
});
}
return response.json();
})
.then((results) => {
const user = results.user;
this.setState({
user,
});
})
.catch((error) => {
console.log("Error", error);
});
}
render() {
console.log(this.state.user);
return (
<div className="container">
<h1 className="is-size-3">Test</h1>
{this.state.user && (
<Route
exact
path="/payments"
render={(props) => <Payments {...props} user={this.state.user} /> }
/>
)}
</div>
);
}
}
Payments.js支付.js
function Payments() {
return (
<>
<CheckoutForm user={this.props.user} />
<CurrentSubscription subscription={subscription} />
</>
);
}
I have tried a few approaches,but still I'm getting 'props' of undefined.我尝试了几种方法,但我仍然得到未定义的“道具”。
Thanks in advance提前致谢
This should work这应该工作
function Payments(props) {
return (
<>
<CheckoutForm user={props.user} />
<CurrentSubscription subscription={subscription} />
</>
);
}
Always put props in the function or class component f you have props, like so:如果你有道具,请始终将道具放在 function 或 class 组件中,如下所示:
function Payments({user}) {
return (
<>
<CheckoutForm user={user} />
<CurrentSubscription subscription={subscription} />
</>
);
}
or要么
function Payments(props) {
return (
<>
<CheckoutForm user={props.user} />
<CurrentSubscription subscription={subscription} />
</>
);
}
By the way, in functional component, there's no this
.顺便说一句,在功能组件中,没有
this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.