这是我的Profile
课:
class Profile extends React.Component {
state={email:'',userName:'',userID:''};
render() {
return(
<div>
...
<Link to={{pathname:"/edit",state:this.props.state}}>
...
</div>
);
}
}
export default Profile;
这是我的
ProfileEdit
类:class ProfileEdit extends React.Component {
state={email:'',userName:'',userID:''};
render() {
return(
<div>
...
<TextField valueOfEmail={this.state.userID}/>
...
</div>
);
}
}
export default ProfileEdit;
这是我的
TextField
类:class TextField extends React.Component {
render() {
const {valueOfEmail}=this.props;
return (
<div>
<div className="form-label-group">
<input type="text" id="inputEmail" value={valueOfEmail} className="form-control" placeholder="Name" required autoFocus/>
<label htmlFor="inputEmail">Enter Name</label>
</div>
</div>
);
}
}
export default TextField;
它有时会给我错误,有时却不会,但是什么也没有。
这是我得到的错误:
我已使用“ react-router-dom”:“ ^ 5.0.1”
如何解决此问题并使用
<Link/>
或更好的方法正确传递值。(redux除外-仍在学习) 最佳答案
尝试将您的参数作为路由器内部的路径url参数传递,因此将路由器组件更改为
<Route path="/edit/:id/:email/:name" component={ProfileEdit} />
或者,如果您不想设置它们,只需将路由器设置为
<Route path="/edit/:id?/:email?/:name?" component={ProfileEdit} />
该链接将是这样的:
<Link to={{pathname:`/edit/${this.state.userID}/${this.state.email}/${this.state.userName}`}}>
然后在
ProfileEdit
组件中使用match道具访问那些信息因此可以像这样访问这些值:
this.state.email = this.props.match.params.email;
this.state.userName = this.props.match.params.name;
this.state.userID = this.props.match.params.id;
还要消除抛出的错误:将onChange(受控)添加到您的输入中,或将其值替换为defaultValue attr(不受控制),有关更多信息,请参见this。
TextField Component的新输入应如下所示
<div className="form-label-group">
<input type="text" id="inputEmail" defaultValue={valueOfEmail} className="form-control" placeholder="Name" required autoFocus/>
<label htmlFor="inputEmail">Enter Name</label>
</div>
如果存在过多的糊状参数,则必须使用商店管理器(url中的糊状参数太丑陋,可能会导致错误)