gpt4 book ai didi

javascript - 使用 React 和 redux 的 Post 方法

转载 作者:行者123 更新时间:2023-12-01 16:17:35 26 4
gpt4 key购买 nike

我有一个用于 CRUD 操作的简单应用程序,现在我可以删除、编辑和显示数据,但我想使用 react 和 redux 将新项目添加到从 API(JSON 服务器假 API)获取的用户列表中。

现在,当我点击添加用户并保存数据时,只会发送 id,但不会发送其他数据。

enter image description here

这是一个现场演示:Redux live demo with source code sandbox .

这是我的表单,AddUserForm.js

import React, { useState } from 'react'
import {useDispatch} from 'react-redux'
import { addNewUser } from '../redux/acitons/users/Users';

function AddUserForm({users}) {
const dispatch = useDispatch();
const [newUserName, setNewUserName] = useState('');

const handleSubmit = (e) =>{
e.preventDefault();

const usersList = users;
const newUserId = usersList[usersList.length - 1].id + 1;

console.log("your name", newUserName);
console.log("your id", newUserId)

dispatch(addNewUser({
...users,
id: newUserId,
name: newUserName,
}));

}

const handleCancel = () => {};
return (
<tr>
<td>{newUserName.id}</td>
<td>
<input
value={newUserName}
name="name"
onChange={e => setNewUserName(e.target.value)}
/>
</td>
<td>
<button type="button" className="btn outline" onClick={handleCancel}>
<i className="material-icons">Cancel</i>
</button>
<button
type="button"
className="btn btn-success btn-link"
onClick={handleSubmit}
>
<i className="material-icons">save</i>
</button>
</td>
</tr>
);
}

export default AddUserForm

我在带有点击按钮的父组件中这样调用。

{adding && <>
<AddUserForm addNewUser={addNewUser} users={userData.users} />
</>}

这是父组件中的一个按钮。

<button
type="button"
className="btn btn-success btn-link btn-add"
onClick={() => setAdding(true)}
>
<i className="material-icons">Add user</i>
</button>

我的代码有什么问题?任何帮助或建议将不胜感激。

最佳答案

在调试工具屏幕截图中,您向我们展示的是响应主体,而不是请求主体。

users是一个数组,为什么这样

dispatch(addNewUser({
...users,
id: newUserId,
name: newUserName,
}));

代替这个?

dispatch(addNewUser({
id: newUserId,
name: newUserName,
}));

问题的根本原因src/redux/acitons/users/Users

export const addNewUser = data => {

console.log("adding mother a new user", data);

return dispatch => {
axios.post("http://localhost:3000/users")

只需更改最后一行

    axios.post("http://localhost:3000/users", data)

我可以在 console.log 中看到 data 而不是在 POST 中。

这会产生空的 usersList 错误。

const newUserId = usersList[usersList.length - 1].id + 1;

希望这对您有所帮助。

关于javascript - 使用 React 和 redux 的 Post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62138082/

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