我有一个用户详细信息页面和一个用户列表页面。只需单击列表页面上的链接,这将在页面底部呈现用户详细信息。如果选择其他用户,则应使用新数据更新组件。似乎react不会更新状态,并且首选用户的数据仍然可见。
class User extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {}
};
this.getUser = this.getUser.bind(this);
}
getUser = id => {
fetch("http://localhost:800/api/v1/users/" + id)
.then(response => response.json())
.then(data => this.setState({ user: data }));
console.log("testing");
};
componentWillMount() {
this.getUser(this.props.match.params.userId);
window.state = this.state;
}
render() {
const { user } = this.state;
return (
<div>
<h3>User Details</h3>
<div class="row">
<div class="alert alert-light">
<p>first name: {user.firstName}</p>
<p>last name: {user.lastName}</p>
<p>email: {user.email}</p>
<p>birthday: {user.birthday}</p>
</div>
</div>
</div>
);
}
}
class UserList extends React.Component {
constructor(props) {
super(props);
this.state = {
userList: []
};
}
componentWillMount() {
fetch("http://localhost:8080/api/v1/users")
.then(response => response.json())
.then(data => this.setState({ userList: data }));
}
render() {
return (
<div>
<h2>Users</h2>
{this.state.userList.map((user, key) => (
<ul>
<li>
<Link to={`${this.props.match.url}/${user.id}`}>
{user.firstName} {user.lastName}
</Link>
</li>
</ul>
))}
<Route path={`${this.props.match.url}/:userId`} component={User} />
<Route
exact
path={this.props.match.url}
render={() => <h3>Select a User!</h3>}
/>
</div>
);
}
}
答案 0 :(得分:1)
componentWillMount
仅在安装组件之前被调用,并且当User
URL参数更改时,不会安装新的userId
组件。
您可以将componentDidUpdate
添加到User
组件中,以在userId
更改时获取新用户。
componentDidUpdate(prevProps){
if (prevProps.match.params.userId !== this.props.match.params.userId) {
this.getUser(this.props.match.params.userId);
}
}