gpt4 book ai didi

javascript - 在 react 中安装后如何设置元素的状态?

转载 作者:行者123 更新时间:2023-11-30 19:41:22 24 4
gpt4 key购买 nike

我有一个包含以下代码的 React 应用程序。在我的用户数据表单中,提交 for 后将显示一条通知消息。通知消息可以是成功消息或失败消息。失败消息可能有几种类型的错误。我正在检查错误的类型并将消息设置为类型。问题是,由于在单击提交按钮之前不会显示通知消息,因此控制台显示“无法在未安装的组件上调用 setState(或 forceUpdate)”。我该如何解决这个问题?

组件:

class Users extends Component {

constructor(props) {
super(props);
this.state = {
successMsg: null,
failMsg: null
};
}

componentDidMount(){
document.getElementById("userSuccess").style.display = "none";
document.getElementById("userFail").style.display = "none";
}

sendData=()=>{
//call AXIOS and call createSuccessMsg() in 'then' & call createFailMsg(errorMsg) in 'catch'
}

createSuccessMsg() {
document.getElementById("userSuccess").style.display = "flex";
this.setState({ successMsg: 'Successfully created!' });
}

createFailMsg(errorMsg) {
document.getElementById("userFail").style.display = "flex";
if ((typeof errorMsg) === "object") {
if (errorMsg.email) {
this.setState({ failMsg: errorMsg.email });
}
if (errorMsg.role) {
this.setState({ failMsg: errorMsg.role });
}
else{
this.setState({ failMsg: errorMsg });
}
}
else {
this.setState({ failMsg: errorMsg });
}
}

render() {
return(
<div>
<div id="userSuccess">{this.state.successMsg}</div>
<div id="userFail">{this.state.failMsg}</div>
<form onSubmit={this.sendData}>
//Inputs
</form>
</div>
)
}

}

最佳答案

先检查 _isMounted:

class Users extends Component {

constructor(props) {
super(props);
this.state = {
successMsg: null,
failMsg: null
};
this._isMounted = false;
}

componentDidMount(){ this._isMounted = true; }


componentWillUnmount() {
this._isMounted = false;
}
componentDidMount(){
document.getElementById("userSuccess").style.display = "none";
document.getElementById("userFail").style.display = "none";
}

sendData=()=>{
//call AXIOS and call createSuccessMsg() in 'then' & call createFailMsg(errorMsg) in 'catch'
}

createSuccessMsg() {
document.getElementById("userSuccess").style.display = "flex";
this._isMounted && this.setState({ successMsg: 'Successfully created!' });
}

createFailMsg(errorMsg) {
document.getElementById("userFail").style.display = "flex";
if ((typeof errorMsg) === "object") {
if (errorMsg.email) {
this._isMounted && this.setState({ failMsg: errorMsg.email });
}
if (errorMsg.role) {
this._isMounted && this.setState({ failMsg: errorMsg.role });
}
else{
this._isMounted && this.setState({ failMsg: errorMsg });
}
}
else {
this._isMounted && this.setState({ failMsg: errorMsg });
}
}

render() {
return(
<div>
<div id="userSuccess">{this.state.successMsg}</div>
<div id="userFail">{this.state.failMsg}</div>
<form onSubmit={this.sendData}>
//Inputs
</form>
</div>
)
}

}

关于javascript - 在 react 中安装后如何设置元素的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55358609/

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