如何使用 axios put 请求在我的 React 应用程序上更新状态?

问题描述 投票:0回答:1

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

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

我查找了有关编辑状态并将其应用于放置请求的帮助指南。我将

editing: false
初始化为状态,创建了一个用于将编辑设置为 true 的处理程序,并对表单中的每个输入执行了 onChange 以便在底部进行编辑。但我发现我不明白 handleUpdating 事件处理程序应如何与 put 连接(我在下面评论了它们),或者我是否需要它。

这是我的文件层次结构:

这是服务器的 put 请求(位于 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;
javascript node.js reactjs axios
1个回答
0
投票
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);

动作/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

==================================== 朋友Dev,这是我为创建CRUD而开发的所有数据,对我来说它工作得很好,我只是在单击记录时遇到困难,并且该记录出现在要编辑的表单中,主要的正在做它的事情, API数据。

祝你学习顺利。

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

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.