【发布时间】:2020-04-13 05:19:14
【问题描述】:
我正在尝试使用 .put 调用来编辑从 API 中提取的颜色数组中的颜色。但是,由于某种原因,我的 .put 调用不起作用。我无法从 .put 调用中获得响应以登录到控制台。当我尝试通过单击保存按钮提交时,我收到一条错误消息,提示 colors.map 不是函数。有谁知道我该如何解决这个问题?
import React, { useState } from "react";
import axios from "axios";
import { axiosWithAuth } from "../utils/axiosWithAuth";
const initialColor = {
color: "",
code: { hex: "" },
};
const ColorList = ({ colors, updateColors }) => {
console.log(colors);
const [editing, setEditing] = useState(false);
const [colorToEdit, setColorToEdit] = useState(initialColor);
const editColor = color => {
setEditing(true);
setColorToEdit(color);
};
const saveEdit = e => {
e.preventDefault();
// Make a put request to save your updated color
// think about where will you get the id from...
// where is is saved right now?
axiosWithAuth().put(`/colors/${colorToEdit.id}`, colorToEdit)
.then(res => {
console.log(res);
updateColors(res.data);
})
};
const deleteColor = color => {
// make a delete request to delete this color
};
return (
<div className="colors-wrap">
<p>colors</p>
<ul>
{colors.map(color => (
<li key={color.color} onClick={() => editColor(color)}>
<span>
<span className="delete" onClick={e => {
e.stopPropagation();
deleteColor(color)
}
}>
x
</span>{" "}
{color.color}
</span>
<div
className="color-box"
style={{ backgroundColor: color.code.hex }}
/>
</li>
))}
</ul>
{editing && (
<form onSubmit={saveEdit}>
<legend>edit color</legend>
<label>
color name:
<input
onChange={e =>
setColorToEdit({ ...colorToEdit, color: e.target.value })
}
value={colorToEdit.color}
/>
</label>
<label>
hex code:
<input
onChange={e =>
setColorToEdit({
...colorToEdit,
code: { hex: e.target.value }
})
}
value={colorToEdit.code.hex}
/>
</label>
<div className="button-row">
<button type="submit">save</button>
<button onClick={() => setEditing(false)}>cancel</button>
</div>
</form>
)}
<div className="spacer" />
{/* stretch - build another form here to add a color */}
</div>
);
};
export default ColorList;
【问题讨论】:
标签: javascript arrays reactjs api object