gpt4 book ai didi

javascript - 如何在我的 React 应用程序上使用 axios put 请求更新状态? ( react /Node express )

转载 作者:行者123 更新时间:2023-11-30 06:23:20 25 4
gpt4 key购买 nike

我一直在审查我的 HTTP/AJAX 项目并且能够实现我的获取、发布和删除。但是我试图自己实现put请求并且已经坚持了两天(我知道)。

我的理解是,在一个事件处理程序中应该有axios请求,然后你绑定(bind)处理程序。我的 put 请求有 id 并且正在更新,但 id (friend.id) 仅被一个空字符串替换。 put 请求在服务器中工作并正确更新数据。所以我发现我的问题出在 React 中。

我查阅了有关编辑状态并将其应用于放置请求的帮助指南。我将 editing: false 初始化为状态,制作了一个用于将 editing 设置为 true 的处理程序,并在底部的表单中对每个输入进行了 onChange 以进行编辑。但是我发现我不明白 handleUpdating 事件处理程序应该如何与 put 连接(我在下面对它们进行了评论),或者我是否需要它。

这是我的文件层次结构: file hierarchy

这是服务器的放置请求(位于 server.js 中):

app.put('/friends/:id', (req, res) => {
const { id } = req.params;
let friendIndex = friends.findIndex(friend => friend.id == id);

if (friendIndex >= 0) {
friends[friendIndex] = { ...friends[friendIndex], ...req.body };
res.status(200).json(friends);
} else {
res
.status(404)
.json({ message: `The friend with id ${id} does not exist.` });
}
});

这是我的 React 应用程序中的代码(位于 Friendslist.js 中):

import React from 'react';
import axios from 'axios';
const API_URL = 'http://localhost:5000/friends';

class FriendsList extends React.Component {
constructor() {
super();
this.state = {
friends: [],
editing: false,
loading: true,
showComponent: false,
name: '',
age: '',
email: ''
}
}

componentDidMount() {
axios
.get(`${API_URL}`)
.then(response => {
console.log(response.data);
this.setState({ friends: response.data, loading: false });
})
.catch(error => {
console.log('There was an error', error);
})
}

onClickComponent = () => {
this.setState({ showComponent: true });
}

handleName = (event) => {
event.preventDefault();
this.setState({
name: event.target.value
});
}

handleAge = (event) => {
event.preventDefault();
this.setState({
age: event.target.value
});
}

handleEmail = (event) => {
event.preventDefault();
this.setState({
email: event.target.value
});
}

// handleUpdating - setting edit to true
handleUpdating = (event) => {
this.setState({ editing: true })
}

onClickComponent = () => {
this.setState({ showComponent: true });
}

handleDelete = (id) => {
axios
.delete(`${API_URL}/${id}`)
.then(response => {
this.setState({
friends: response.data
})
console.log(response.data)
})
.catch(error => {
console.log(error)
})
};

handleSubmit = (event) => {
event.preventDefault();
axios.post(`${API_URL}`, {
name: this.state.name,
age: this.state.age,
email: this.state.email
})
.then(response => {
this.setState({ friends: response.data });
})
.catch(error => {
console.log(error);
});
}


// This is the put request
handleEdit = (id) => {
axios.put(`${API_URL}/${id}`, {
name: this.state.name,
age: this.state.age,
email: this.state.email
})
.then(response => {
this.setState({ friends: response.data });
})
.catch(error => {
console.log(error);
});
}

render() {
if (this.state.loading) {
return <h1>Loading Friends....</h1>
} else if (!this.state.loading) {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.name} onChange={this.handleName} />
</label>
<label>
Age:
<input type="text" value={this.state.age} onChange={this.handleAge} />
</label>
<label>
Email:
<input type="text" value={this.state.email} onChange={this.handleEmail} />
</label>
<input type="submit" value="Submit" />
</form>


<div>{this.state.friends.map((friend) => {
return (
<div onChange={() => this.handleUpdating} key={friend.id} className="friend">
<div className="friend-name">{friend.name}</div>
<div className="friend-age">{`Age: ${friend.age}`}</div>
<div className="friend-email">{`Email: ${friend.email}`}</div>
<button onClick={() => this.handleDelete(friend.id)}>Delete</button>
<button onClick={this.onClickComponent}>Edit</button>
{this.state.showComponent ? <Form handleEdit={() => this.handleEdit(friend.id)} /> : null}
</div>
);
})}
</div>
</div>
);
}

}
}



const Form = (props) => {
return (
<form onSubmit={() => props.handleEdit(props.id)}>
<label>
Name: <input type="text" value={props.name} onChange={this.handleUpdating} />
</label>
<label>
Age: <input type="text" value={props.age} onChange={this.handleUpdating} />
</label>
<label>
Email: <input type="text" value={props.email} onChange={this.handleUpdating} />
</label>
<input type="submit" value="Update" />
</form>
);
}

export default FriendsList;

感谢任何帮助和/或反馈!

最佳答案

enter code here
import { connect } from 'react-redux';
import api from '../../services/api';
import * as actions from '../../store/actions';


updateTool = (id) => {
console.tron.log('edit !!!');
this.setState({ isEdit: true });

const modifyTool = {
id: this.props.id,
title: this.state.title,
link: this.state.link,
description: this.state.description,
tags: this.state.tags,
};

api
.put(`/tools/${id}`, modifyTool)
.then((res) => {
console.log(res.data);
})
.catch((error) => {
console.log(error);
});
};

{/* form Modal Update */}
<section>
<Modal
visible={this.state.showModal}
width="400"
height="370"
effect="fadeInUp"
onClickAway={() => this.closeModal()}
>
<FormModal>
<form onSubmit={this.updateTool}>
<div>
<span>Update tool</span>

<label>Tool Name</label>
<input
type="text"
onChange={this.handleChange}
value={tool.title}
name="title"
/>
<label>Tool Link</label>
<input
type="text"
onChange={this.handleChange}
value={this.props.link}
name="link"
/>

<label>Tool description</label>
<textarea
cols={20}
rows={5}
name="description"
onChange={this.handleChange}
value={this.state.description}
/>
<label>Tags</label>
<input
type="text"
onChange={this.handleChange}
value={this.state.tags}
name="tags"
/>
</div>
<AlignHorizontalRight>
<button>Cancel</button>
<div>
<input
type="button"
value="EDIT"
type="submit"
onClick={() => this.updateTool(tool.id)}
/>
</div>
</AlignHorizontalRight>
</form>
</FormModal>
</Modal>
</section>

const mapDispatchToProps = dispatch => ({
removeTool: (id) => {
dispatch(actions.removeTool(id));
},
updateTool: (id, title, link, description, tags) => {
dispatch(actions.updateTool(id, title, link, description, tags));
},
});
export default connect(
null,
mapDispatchToProps,
)(Content);

Action /index.js

export const ADD_TOOL = 'ADD_TOOL';
export const REMOVE_TOOL = 'REMOVE_TOOL';
export const UPDATE_TOOL = 'UPDATE_TOOL';

const nextId = 0;

export function addTool(title, link, description, tags) {
return {
type: ADD_TOOL,
id: nextId,
title,
link,
description,
tags,
};
}

export function removeTool(id) {
return {
type: REMOVE_TOOL,
id,
};
}

export function updateTool(id, title, link, description, tags) {
return {
type: UPDATE_TOOL,
id,
title,
link,
description,
tags,
};
}

商店/index.js

import { createStore } from 'redux';

const store = createStore(() => {});

export default store;

reducers/index.js

import { combineReducers } from 'redux';
import tool from './tool';



const store = combineReducers({
tool,
});

export default store;

reducers/tool.js

import { ADD_TOOL, REMOVE_TOOL, UPDATE_TOOL } from '../actions';

const INITIAL_STATE = [];

export default function Tool(state = INITIAL_STATE, action) {
switch (action.type) {
case ADD_TOOL:
return [
...state,
{
id: action.id,
title: action.title,
link: action.link,
description: action.description,
tags: action.tags,
},
];
case REMOVE_TOOL:
return state.filter(({ id }) => id !== action.id);
case UPDATE_TOOL:
return state.map(tool => (tool.id === action.id ? { ...tool, ...action } : tool));
default:
return state;
}
}

enter code here

================================= friend Dev,这是我为创建 CRUD 而开发的所有数据,对我来说它工作正常,我只是难以单击记录,并且该记录出现在要编辑的表单中,主要的是做它是什么, API 数据。

祝你学业顺利。

注意:我假设您已经知道如何使用上述数据,它不按顺序排列,但只需正确编码或粘贴即可。

关于javascript - 如何在我的 React 应用程序上使用 axios put 请求更新状态? ( react /Node express ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51846281/

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