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

时间:2018-08-14 16:49:08

标签: javascript node.js reactjs axios

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

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

我查阅了有关编辑状态并将其应用于放置请求的帮助指南。我将editing: false初始化为状态,做了一个将编辑设置为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;

感谢您的帮助和/或反馈!

1 个答案:

答案 0 :(得分: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);

actions / 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,
  };
}

store / 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数据。

祝你学习顺利。

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