反应)“this.props”,同时使用路由器共享“状态”
Posted
技术标签:
【中文标题】反应)“this.props”,同时使用路由器共享“状态”【英文标题】:React) "this.props" while sharing the "state" using router 【发布时间】:2021-05-15 05:10:18 【问题描述】:谁来帮帮我:(
我在结果页面上找不到“this.props.Epoint”。
这就像“Epoint:”“IPoint:”。空的,空的。
我必须收到“Epoint : 0”、“IPoint :”,不是吗?
这里是代码。请救救我。
<App.js>
class App extends Component
state =
EPoint: 0,
IPoint: 0,
;
upEPoint = async () =>
this.setState(
Epoint: this.state.EPoint ++
)
;
upIPoint = async () =>
this.setState(
Ipoint: this.state.IPoint ++
)
;
render()
return (
<>
<Router>
<Route exact path="/" component=Home />
<Route path="/question1" component=() => <Question1 EPoint=this.state.EPoint IPoint=this.state.IPoint upEPoint=this.upEPoint upIPoint=this.upIPoint/> />
<Route path="/question2" component=() => <Question2 EPoint=this.state.EPoint IPoint=this.state.IPoint upEPoint=this.upEPoint upIPoint=this.upIPoint/> />
<Route path="/question3" component=() => <Question3 EPoint=this.state.EPoint IPoint=this.state.IPoint upEPoint=this.upEPoint upIPoint=this.upIPoint/> />
<Route path="/result" component=() => <Result EPoint=this.state.EPoint IPoint=this.state.IPoint/> />
<Router/>
</>
export default App;
<Result.js>
class Result extends Component
render()
return (
<div>
<header>
<h1> Result </h1>
<h5> Epoint : this.props.Epoint</h5>
<h5> Ipoint : this.props.Ipoint</h5>
</header>
</div>)
export default Result;
【问题讨论】:
【参考方案1】:我认为这里的第一个问题是你试图从 props 访问 Epoint,但是你在 props 中传递的 state 变量实际上是 EPoint(注意那里的大写 P)。 IPoint 也是如此。
您的 Result.js 应该如下所示:
import React from "react";
class Result extends React.Component
render()
return (
<div>
<header>
<h1> Result </h1>
<h5> Epoint : this.props.EPoint</h5>
<h5> Ipoint : this.props.IPoint</h5>
</header>
</div>
);
export default Result;
正如其他答案也提到的那样,您不能像现在一样设置您的状态。 我对类组件不太擅长,但我相信您必须将其设置为如下所示:
constructor(props)
super(props);
this.state = EPoint: 0, IPoint: 0 ;
【讨论】:
神圣...非常感谢【参考方案2】:你不能在 setState 中使用 this.state 只是从箭头函数获取 prev 状态然后将其分配给新对象并将其返回到 setState
upIPoint = async () =>
this.setState(prev => (
Ipoint: prev.IPoint + 1
)
;
【讨论】:
以上是关于反应)“this.props”,同时使用路由器共享“状态”的主要内容,如果未能解决你的问题,请参考以下文章