gpt4 book ai didi

javascript - ReactJS 在不刷新浏览器的情况下检查数据库的更改和更新组件

转载 作者:行者123 更新时间:2023-11-30 08:23:43 26 4
gpt4 key购买 nike

在运行编辑功能并成功更新数据库后,我无法弄清楚如何使用数据库中的新数据更新组件。

我已经尝试执行 this.forceUpdate() 但它不起作用。我听说过使用 this.setState() 但我不知道如何使用数据库更新它,因为我的类状态是一个 JSON 数组。

几天来我一直在思考和搜索,但没有任何运气,所以非常感谢任何建议或帮助解决这个问题。

附言我正在为我的数据库使用 MySQL。我不知道这是否重要。

App.js

import React, { Component } from 'react';
import './App.css';

class App extends Component {

constructor(props) {
super(props);
this.state = {
toggle: false,
toggleIdxArray: [],
classroom: [],
childflagged: '',
flagreason: '',
id: ''
};
this.eventHandler = this.eventHandler.bind(this);
this.logChange = this.logChange.bind(this);
this.handleEdit = this.handleEdit.bind(this);
}

logChange(e) {
this.setState({
[e.target.name]: e.target.value
});
}

handleEdit(event) {
event.preventDefault()
var data = {
childflagged: this.state.childflagged,
flagreason: this.state.flagreason,
id: this.state.id
}
fetch("/classroom/edit", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
}).then(function(data) {
if (data.affectedRows === 1) {
console.log('Edited Flag!'); //UPDATE COMPONENT FUNCTION OF SOME-SORT HERE
}
}).catch(function(err) {
console.log(err)
});

}

eventHandler(event, idx) {
let updatedArr = this.state.toggleIdxArray.slice();
let checkIdx = updatedArr.indexOf(idx);
if (checkIdx === -1) updatedArr.push(idx);
else updatedArr.splice(checkIdx, 1);
this.setState((prevState) => ({
toggleIdxArray: updatedArr
})
);
}

componentDidMount() {
fetch("/classroom")
.then(res => res.json())
.then(classroom => this.setState({ classroom }))
}

render() {
return (
<div className="App">
<div className="wrapper">
<h1>Classroom</h1>
{this.state.classroom.map((classroom, idx) =>
<div className="child" key={classroom.id}>
<p className="detail">Child's Name: <span className={classroom.childflagged}>{classroom.childsname}</span> <i title={classroom.flagreason} className={'fa fa-flag flag' + classroom.childflagged}></i><i title={classroom.starreason} className={'fa fa-star star' + classroom.starstudent}></i></p>
<p className="detail">Parent's Phone Number: {classroom.parentsnumber}</p>
<div className="actionMenu">
<button className="flags" id={classroom.id} onClick={e => this.eventHandler(e, idx)}>Edit Flags</button>
<button className="results">View Results</button>
<button className="profile">View Profile</button>
</div>
<div className="actionForm">
<div>
<form id={"flagform" + classroom.id} className={this.state.toggleIdxArray.includes(idx) ? '' : 'hide'} onSubmit={this.handleEdit} method="post" autoComplete="no">
<input type="hidden" name="id" value={classroom.id} />
<input type="text" onChange={this.logChange} value={this.state.childflagged} name="childflagged" placeholder="Flag Type" />
<input type="text" onChange={this.logChange} value={this.state.flagreason} name="flagreason" placeholder="Reason For Flag" />
<input type="submit" onClick={() => this.state.id = classroom.id} name="submit" value="Save Changes" />
</form>
</div>
</div>
</div>
)}
</div>
</div>
);
}
}

export default App;

最佳答案

如果在数据库上更新数据后以有用的格式取回数据,只需对该数据使用 setState:

handleEdit(event) {
event.preventDefault()
var data = {
childflagged: this.state.childflagged,
flagreason: this.state.flagreason,
id: this.state.id
}
fetch("/classroom/edit", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(function(response) {
if (response.status >= 400) {
//Aside: because of the way promises work, this is the correct way to throw the error. Doing this you can catch it in the "catch" callback
Promise.reject(new Error("Bad response from server"));
}
return response.json();
}).then((data) => {
if (data.affectedRows === 1) {
console.log('Edited Flag!'); //UPDATE COMPONENT FUNCTION OF SOME-SORT HERE
//use data to set state
this.setState({ classroom: data });
}
}).catch(function(err) {
console.log(err)
});

}

关于javascript - ReactJS 在不刷新浏览器的情况下检查数据库的更改和更新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49288531/

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