gpt4 book ai didi

javascript - 如何在 React 中使用 POST 方法将对象添加到数据库?

转载 作者:行者123 更新时间:2023-12-02 23:29:47 25 4
gpt4 key购买 nike

预期结果:创建假 API --> 调用函数 save--> 方法 POST --> 将对象 time 保存到 this.state.resul --> 保存 db.json todos id 2

我正在使用库Fake an API with JSON Server

db.json

{
"todos": [
{
"id": 1,
"title": "AAAA"
"results": [
{
"time": "09:10:01",
"desc": "bbbbb"
},
{
"desc": "gfgfgfgffg",
"time": "21:30:06"
}
]
},
{
"id": 2,
"title": "BBBBBBB",
"results": [
{
"time": "09:10:01",
"desc": "reerrererer",
},
{
"desc": "dfdfdfdfdfdfdfdfdfdfdf",
"time": "21:30:06"
}
]
}
}

待办事项

class Todos extends Component {
constructor (props) {
super(props);
this.state = {
todos: []
}
}

componentDidMount() {
axios.get("http://localhost:3000/todos")
.then(response => {
this.setState({
todos: response.data
});
})
.catch(error => {
console.log('Error);
}
);
}

render () {
return(
)
}
}
export default Todos;

秒表

class StopWatch extends Component {
constructor() {
super();

this.state = {
resul: []
};

}


save = () => {
const resul = this.state.resul;
this.clock = {
clock: this.clock
}
resul.push(this.clock);

this.setState({
resul
});

axios.post(`http://localhost:4000/todos/2`, {
results: this.clock
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}


render () {
return (
<ul className="results">


{
this.state.resul
.map((item, index) =>
<Time
key= {index}
/>
)
}
</ul>
);
}
}


export default StopWatch;

最佳答案

使用put更新数组,并传递要更新的整个对象。

save = () =>{
const resul = JSON.parse(JSON.stringify(this.state.resul));

this.clock = {
clock: this.clock
};
resul.push(this.clock);

this.setState({
resul
});

const todo = {
id: 2,
title: 'BBBBBBB',
results: resul
};

axios
.put(`http://localhost:4000/todos/2`, todo)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}

关于javascript - 如何在 React 中使用 POST 方法将对象添加到数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56563817/

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