我正在运行一个带有 Firebase 的 React 应用程序。我有一个端点“/items”。
当我通过 Axios 调用 DELETE 请求时,数据库反射(reflect)了正确的数据。但是,在 DELETE 请求之后,当我调用 GET 请求来检索更新的“项目”时,我会在已删除项目所在的位置得到一个空引用,从而导致空引用错误。
EXAMPLE
-Original [item1, item2, item3]
*Delete item2
-Get
- [item1, null, item3]
但是在 Firebase 上它会正确反射(reflect)..
class VendingMachine extends Component {
state = {
balance: "",
items: [],
}
getItems = () => {
axios.get('items.json')
.then(response => {
if (response.data) {
this.setState({ items: Object.values(response.data) });
}
})
}
deleteItemHandler = (id) => {
axios.delete('/items/' + id + '.json')
.then((response) => {
this.getItems();
});
}
Put 请求位于另一个组件中..
class NewItem extends Component {
errorElement = React.createRef();
state = {
newItem: {
name: "",
position: null,
price: "",
image: ""
},
showError: false
};
addItemHandler = () => {
if (this.props.items.length === 9) {
this.setState({ showError: true });
return;
}
const newItem = {
id: this.props.items.length,
name: this.state.newItem.name,
price: this.state.newItem.price,
image: this.state.newItem.image,
position: this.props.items.length
}
console.log(newItem);
axios.put('/items/' + newItem.id + '.json', newItem)
.then(response => {
this.props.updateItems()
})
.catch(error => console.log(error));
}
最佳答案
这是在 Firebase 中存储数组时的预期行为。
当您存储时:
["item1", "item2", "item3"]
Firebase 数据库服务器实际上将其存储为:
{
"0": "item1",
"1": "item2",
"2": "item3"
}
然后意味着当您删除 item2
时,您最终会得到:
{
"0": "item1",
null,
"2": "item3"
}
Firebase 客户端随后将其转换回:
["item1", null, "item3"]
您有两个选择:
- 始终更新整个数组
- 使用集合而不是数组
始终更新整个数组
如果您想继续将项目存储为数组,则必须在删除的项目之后对所有项目的索引重新编号。因此,这意味着对数组的任何更新都意味着您需要读取然后写入整个数组。
<小时/>使用集合而不是数组
但您实际上可能没有存储数组。许多开发人员使用数组来存储类似集合的数据结构,即唯一项的无序集合。例如:["item3", "item2", "item1"]
与 ["item1", "item2", "item3"]
的含义相同吗? ["item1", "item1", "item2", "item3"]
在您的应用中实际上是非法的吗?如果是这样,您正在查看类似集合的数据结构,它在 Firebase 中更好地映射到:
{
"item1": true,
"item2": true,
"item3": true
}
true
值没有意义,只是因为 Firebase 不会存储没有值的键,所以才需要该值。但除此之外,这是存储此类集合的最佳结构。如果您从中删除 item2
,Firebase 将仅返回没有该键的对象:
{
"item1": true,
"item2": true,
"item3": true
}
<小时/>
有关此内容的更多信息,另请参阅:
关于javascript - DELETE 后 GET 时 Firebase 返回空引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54138520/