我正在学习React,对这个问题我一无所知。我有一个包含三列的数据库:
一切正常,但一项:更新项目。我只想将“打包”值更新为“真”或“假”值。它可以在带有REST API的Swagger中正常工作。现在,我想尝试清除React。这是我的代码:
import React from 'react';
class ClothesList extends React.Component {
constructor(props) {
super(props);
this.state = {
id: '',
item: '',
packed: false,
clothes: [],
error: null
};
this.deleteClothes = this.deleteClothes.bind(this);
this.updateItem = this.updateItem.bind(this);
}
componentDidMount() {
fetch('/api/v1/clothes')
.then(response => response.json())
.then(
data => {
this.setState({
clothes: data
});
},
error => {
this.setState({
error
});
}
)
}
deleteClothes(id) {
fetch(`/api/v1/clothes/${id}`, {
method: 'DELETE'
}).then(() => {
let updatedClothes = [...this.state.clothes].filter(i => i.id !== id);
this.setState({
clothes: updatedClothes,
});
});
}
updateItem(id) {
const { item, packed } = this.state;
fetch(`/api/v1/clothes/${id}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ item, packed })
});
}
render() {
const { clothes, error } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
}
const clothesList = clothes.map(c => {
return <tr key={c.id}>
<td>{c.id}</td>
<td>{c.item}</td>
<td>{c.packed === true ? <span>Yes</span> : null}</td>
<td><button className="btn btn-danger" onClick={() => this.deleteClothes(c.id)}>Delete</button>
<button className="btn btn-primary" onClick={() => this.updateItem(c.id)}>Update Item</button>
</td>
</tr>
});
return (
<div>
<h3>Clothes</h3>
<table className="table">
<thead>
<tr>
<th>ID</th>
<th>Item</th>
<th>Packed</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{clothesList}
</tbody>
</table>
</div>
);
}
}
export default ClothesList;
感谢您的帮助...
组件中没有设置为ID和打包状态的任何内容
updateItem(id) {
this.setState({
...this.state,
packed: true,
id,
})
const { item, packed } = this.state;
fetch(`/api/v1/clothes/${id}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ item, packed })
});
}