gpt4 book ai didi

javascript - 通过路由将 props 传递到页面的问题

转载 作者:行者123 更新时间:2023-12-02 14:10:34 25 4
gpt4 key购买 nike

我是 ReactJs 的新手。我创建了一个小型应用程序,它用用户填充网格,单击与用户关联的按钮后,该应用程序将重定向到包含有关用户的信息(作为 props 传递)的页面。我使用了路由器来处理此页面请求:

<Router>
<Route path="/" header="Main Page" component={() => (<MainPage content={users}/>)}>
</Route>
<Route path="/UserName" header="User Page" component={UserPage}/>
</Router>

网格页面可以正常工作并从父组件获取数据作为 prop,如下所示:

var React = require('react');
var ReactRouter = require('react-router');
var Link = ReactRouter.Link;
var Prompt = require('../components/Prompt');

var UsersList = React.createClass({
accessUserInfo: function (user) {
this.context.router.push('/UserName', query={user});
},
render: function(){
return(
<form>
<table>
<tbody>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Day of Birth</th>
<th>Username</th>
<th>Role</th>
<th></th>
</tr>
{this.props.content.map(function(user, i) {
return (
<tr key={i}>
<td>{user.name}</td>
<td>{user.surname}</td>
<td>{user.birthday}</td>
<td>{user.userName}</td>
<td>{user.userRole}</td>
<td>
<Link>
<button type="submit" onSubmit={this.accessUserInfo(user)}>Open</button>
</Link>
</td>
</tr>
);
}.bind(this))}
</tbody>
</table>
</form>
)
}

})

UsersList.contextTypes = {
router: React.PropTypes.object.isRequired
}

module.exports = UsersList;

非常基本的用户页面如下:

var React = require('react');

var UserPage = React.createClass({
render: function () {
return(
<table>
<tbody>
<h1>
Information for User {this.props.user.userName}
</h1>
<tr>
<td>Name: </td>
<td>{this.props.user.name}</td>
</tr>
<tr>
<td>Surname: </td>
<td>{this.props.user.surname}</td>
</tr>
<tr>
<td>Role: </td>
<td>{this.props.user.userRole}</td>
</tr>
</tbody>
</table>
)

}});

module.exports = UserPage;

我有两个问题:

  • 无论单击哪个按钮,都会为数组中的每个项目调用 accessUserInfo() 方法
  • 用户页面加载,但用户 Prop 未传递给组件,正如我得到的

cannot read property 'userName' of undefined

任何帮助将不胜感激,提前致谢

最佳答案

避免 accessUserInfo()为每个项目调用,使用箭头函数 sintax:onSubmit={()=>this.accessUserInfo(user)}

但我认为您不需要该方法,并且需要稍微更改您的设计,因为您无法将对象作为属性发送。例如,如果您要发送用户的 ID(以便从商店或 API 获取 UserPage 组件上的用户),则可以直接使用链接设置属性。已解释here 。只需使用,例如

<Link to={"UserName/"+userId}></Link>

将路线更改为类似

之后

<Route path="/UserName/:userId" header="User Page" component={UserPage}/>

关于javascript - 通过路由将 props 传递到页面的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39642405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com