更新用户名后不重新呈现配置文件页面



我开始学习 React。更改名称后,配置文件页面不会更新。 请求正在处理中,我得到了想要的结果,用户名已更新,但个人资料页面没有重新加载,请告诉我如何解决它。事实是我在用户记录的页面上也有类似的问题,并且在添加记录时也有类似的情况,它在重新加载页面后也会出现。我是否没有导致组件更新成功?

元件:

import React, { Component } from 'react';
import {connect} from 'react-redux';
import {users} from "../actions";

class ProfilePage extends Component {
state = {
text: ""
};
submitName = (e) => {
e.preventDefault();
this.props.updateName(this.props.user.id, this.state.text).then(this.resetForm);
this.setState({text: ""});
};
render() {
return (
<div>
<div>
<h3>{this.props.user.username}</h3>
<span>Edit name</span>
<form onSubmit={this.submitName}>
<input
value={this.state.text}
placeholder="Enter note here..."
onChange={(e) => this.setState({text: e.target.value})}
required />
<input type="submit" value="Save Name" />
</form>
</div>
<p>{this.props.user.id}</p>
</div>
)
};
}
const mapStateToProps = state => {
return {
user: state.auth.user,
}
};
const mapDispatchToProps = dispatch => {
return {
updateName: (id, newname) => {
return dispatch(users.updateName(id, newname));
},
}
};
export default connect(mapStateToProps, mapDispatchToProps)(ProfilePage);

行动:

export const updateName = (userId, newname) => {
return (dispatch, getState) => {
let headers = {"Content-Type": "application/json", 'Access-Control-Allow-Origin': 'http://localhost:3000'};
let {token} = getState().auth;
if (token) {
headers["Authorization"] = `Token ${token}`;
}
let body = JSON.stringify({"username":newname});
return fetch(`/api/users/${userId}/`, {headers, method: "PUT", body})
.then(res => {
if (res.status < 500) {
return res.json().then(data => {
return {status: res.status, data};
})
} else {
console.log("Server Error!");
throw res;
}
})
.then(res => {
if (res.status === 200) {
return dispatch({type: 'UPDATE_USERNAME', user: res.data, userId});
} else if (res.status === 401 || res.status === 403) {
dispatch({type: "AUTHENTICATION_ERROR", data: res.data});
throw res.data;
}
})
}
};

还原剂:

const initialState = [];
export default function users(state=initialState, action) {
switch (action.type) {
case 'FETCH_USER':
return [...state, ...action.user];
case 'UPDATE_USERNAME':
return [...state, ...action.user];
default:
return state;
}

}

使用 Redux,您正在更新道具,这不会触发页面的渲染。 请确保在更新道具后进行状态更改,如果您尚未在 resetForm 函数中进行更改。

this.props.updateName(this.props.user.id, this.state.text)
.then(()=>{this.resetForm(); this.setState({text: ""});
});

或者,您可以在更新道具后使用此.forceUpdate。 另一种选择是使用 getDerivedStateFromProps 函数。每当道具发生变化时,都会调用此名称。如果此函数中返回状态更改,则页面将呈现。

相关内容

最新更新