将 React 类重构为 hooks - 实体更新组件

我有这个用于更新业务实体的 React 组件。它基本上通过 componentDidMount 上的 ID 获取,并在提交表单时发送放置请求。我想将其重构为基于钩子的组件。


这是之前的代码


import React from "react";

import axios from "axios";


//Api Helper Methods

const API_HOST = "https://api.example.com";

const get = (endPoint) =>

  axios

    .get(`${API_HOST}/${endPoint}`)

    .then((response) => response.data);


export const put = (endPoint, payload, id) =>

  axios

    .put(`${API_HOST}/${endPoint}/${id}`, payload)

    .then((response) => response.data);


//React route (uses React Router)

const END_POINT = `users`;


class Entity extends React.Component {


  state = { entity: {}, fetching: true };


  getEntity = async () => {

    const { id } = this.props.match.params;

    this.setState({ fetching: true });

    const entity = await get(`${END_POINT}/${id}`);

    this.setState({ entity, fetching: false });

  };


  onChange = (key, value) =>

    this.setState({ entity: { ...this.state.entity, [key]: value } });


  componentDidMount() {

    this.getEntity();

  }


  onSubmit = async (e) => {

    e.preventDefault();

    let { entity } = this.state;

    let { match } = this.props;

    await put(END_POINT, entity, match.params.id);

  };


  render() {

    const { entity, fetching } = this.state;


    if (fetching) {

      return <p>loading...</p>;

    }


    return (

      <form onSubmit={this.onSubmit}>

        <label htmlFor="name">name</label>

        <input

          value={entity["name"]}

          onChange={(e) => this.onChange("name", e.target.value)}

        />

        <button type="submit">submit</button>

      </form>

    );

  }

}


export default Entity;

这是我到目前为止的代码。下一步是提取自定义挂钩。


const END_POINT = `users`;


export default function Entity({ match }) {

  const [entity, setEntity] = useState({ name: "" });

  const [fetching, setFetching] = useState( true );

  const { id } = match.params;


  const onChange = (key, value) => setEntity({ ...entity, [key]: value });



慕神8447489
浏览 108回答 2
2回答

尚方宝剑之说

我没有对此进行测试,但这应该接近您想要的实体函数自定义挂钩。import React, { useEffect, useState } from 'react';const API_HOST = "https://api.example.com";const END_POINT = `users`;function useEntity(entityID) {&nbsp; &nbsp; const [entity, setEntity] = useState({})&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; &nbsp; (async () => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; await fetch(`${API_HOST}/${END_POINT}/${props.match.params}`)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(async res => await res.json())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then(result => setEntity(result));&nbsp; &nbsp; &nbsp; &nbsp; })();&nbsp; &nbsp; }, [])&nbsp; &nbsp; return entity}export default function Entity(props) {&nbsp; &nbsp; const { id } = props.match;&nbsp; &nbsp; const entity = useEntity(id);&nbsp; &nbsp; const onSubmit = async () => await fetch(`${API_HOST}/${END_POINT}/${id}`, {method: 'PUT', body: entity})&nbsp; &nbsp; if (!entity) {&nbsp; &nbsp; &nbsp; &nbsp; return <p>loading...</p>;&nbsp; &nbsp; }&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; <form onSubmit={onSubmit}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label htmlFor="name">name</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; value={entity["name"]}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; onChange={(e) => setEntity({ ...entity, name: e.target.value})}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button type="submit">submit</button>&nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; )}

千万里不及你

我让它像这样工作。import React, {useEffect, useState} from "react";import axios from "axios";//Api Helper Methodsconst API_HOST = "https://api.example.com";const get = (endPoint) =>&nbsp; axios.get(`${API_HOST}/${endPoint}`).then((response) => response.data);export const put = (endPoint, payload, id) =>&nbsp; axios&nbsp; &nbsp; .put(`${API_HOST}/${endPoint}/${id}`, payload)&nbsp; &nbsp; .then((response) => response.data);const END_POINT = `users`;const useEntity = (entityId) => {&nbsp; const [entity, setEntity] = useState({ name: "" });&nbsp; const [fetching, setFetching] = useState(true);&nbsp; useEffect(() => {&nbsp; &nbsp; &nbsp; (async () => {&nbsp; &nbsp; &nbsp; &nbsp; const entity = await get(`${END_POINT}/${entityId}`);&nbsp; &nbsp; &nbsp; &nbsp; setEntity(entity);&nbsp; &nbsp; &nbsp; &nbsp; setFetching(false);&nbsp; &nbsp; })();&nbsp; }, [entityId]);&nbsp; return [entity, fetching, setEntity];};//React route (uses React Router)export default function Entity({ match }) {&nbsp; const { id } = match.params;&nbsp; const [entity, fetching, setEntity] = useEntity(id);&nbsp; const onChange = (key, value) => setEntity({ ...entity, [key]: value });&nbsp; const onSubmit = async (e) => {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; await put(END_POINT, entity, id);&nbsp; };&nbsp; if (fetching) {&nbsp; &nbsp; return <p>loading...</p>;&nbsp; }&nbsp; return (&nbsp; &nbsp; <form onSubmit={onSubmit}>&nbsp; &nbsp; &nbsp; <label htmlFor="name">name</label>&nbsp; &nbsp; &nbsp; <input&nbsp; &nbsp; &nbsp; &nbsp; value={entity["name"]}&nbsp; &nbsp; &nbsp; &nbsp; onChange={(e) => onChange("name", e.target.value)}&nbsp; &nbsp; &nbsp; />&nbsp; &nbsp; &nbsp; <button type="submit">submit</button>&nbsp; &nbsp; </form>&nbsp; );}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript