React -customers.map 不是一个函数
我的问题是:当我尝试更改输入时,它会抛出customers.map 不是函数。我想更改值并更新数据库中的数据。
//hook for fetching
const [customers, setCustomers] = useState([]);
//fetching data from db by id
useEffect(() => {
Axios.get(`http://localhost:3001/profile/${id}`)
.then((response) => {
if (response) {
setCustomers(response.data);
}
else {
alert('Error')
}
})
}, [])
这是我尝试映射的方式,否则看起来好像是 onChange 方法导致了问题。
{customers.map(customer =>
<div key={customer.id}>
<div className="containerProfile">
<div className="leftInputProfile">
<p>Full Name</p>
<input type="text" name='Fullname' placeholder={!customer.Fullname && "Adja meg az adatot"}
onChange={(e) => {
setCustomers({ ...customers, [e.target.name]: e.target.value });
}}
/>
</div>
</div>
</div>
我知道, .map()
方法必须获取一个数组,但我不知道这里的解决方案:(
response.data:
My problem is: when I try to change the inputs it throw customers.map is not a function. I'd like to change value and update data in the database.
//hook for fetching
const [customers, setCustomers] = useState([]);
//fetching data from db by id
useEffect(() => {
Axios.get(`http://localhost:3001/profile/${id}`)
.then((response) => {
if (response) {
setCustomers(response.data);
}
else {
alert('Error')
}
})
}, [])
And here is how I try to map, otherwise it seems like, onChange method causes the problem.
{customers.map(customer =>
<div key={customer.id}>
<div className="containerProfile">
<div className="leftInputProfile">
<p>Full Name</p>
<input type="text" name='Fullname' placeholder={!customer.Fullname && "Adja meg az adatot"}
onChange={(e) => {
setCustomers({ ...customers, [e.target.name]: e.target.value });
}}
/>
</div>
</div>
</div>
I know that, .map()
method have to get an array, but I don't know the solution here :(
response.data:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将状态设置为一个对象:
如果您想更新特定客户,您可以编写一个单独的处理程序,例如:
您必须找到要更新的对象,更新它并将其替换为当前状态。
您的输入至少应具有
您必须分配
值
属性,因为您将其设为 受控组件 与您的输入元素。You're setting the state to become an object:
If you want to update a specific customer you could write a separate handler such as:
You have to find the object to update, update it and replace it in the current state.
Your input should have at least
<input name='Fullname' onChange={updateCustomer(customer.id)} value={customer.Fullname} />
You have to assign the
value
property too, as you're making it a controlled component with your input element.我认为你的问题是在你的 onChange 事件中,你通过调用将你的客户设置为一个没有 .map 函数的对象 {}
你必须用方括号 [] 而不是大括号 { 来调用它}:
I think your problem is in your onChange event you are setting your customers to an object {} which does not have the .map function by calling
You have to call it with brackets [] instead of curly braces {}: