【问题标题】:React functional component : can we setState on form load eventReact 功能组件:我们可以在表单加载事件上设置状态吗
【发布时间】:2020-07-23 10:12:45
【问题描述】:

用钩子反应组件:

要求:页面加载时,数据会从后端填充到下拉列表和多选表格(带有复选框的表格)中。单击提交按钮时,我需要使用此合并对象(对于选择的默认值)进行另一个 REST 调用。

注意:没有为这些 ui 组件调用任何更改处理程序。

问题:

  1. 根本没有设置状态,如果我尝试它会进入无限循环。因为它会一次又一次地呈现页面。
  2. 如果我尝试设置状态并使用它,作为异步调用,当时状态不可用。

需要建议:有没有办法在表单加载事件中设置默认选定值的状态。

const [data, setData] = useState(undefined);
const changeRequests = useSelector(state => 
  state.oncallRequest.changeRequests
);

useEffect(() => {
  if (!changeRequests.fulfilled) {
    dispatch(fetchRequests(), [dispatch])
      .then(response => setData(setDefaultState(response.data)));
  }
}, [changeRequests.fulfilled, dispatch]);

我收到以下错误:

ERROR: TypeError: Cannot read property 'then' of undefined.async call.

动作类:

export const fetchRequests = () => dispatch => {
    dispatch({type: LIST_PENDING});

    listChangeRequests().then(data => {
        dispatch({type: LIST_FULFILLED, changeRequests: data})
    }).catch(err => {
        dispatch({type: LIST_FAILED, changeRequests: {error: err.message}})
    });
};

**Service Class**
export const listChangeRequests = () => axiosInstance.get(`/getData`).then(res => {
    return res.data;
});

SOLUTION:
I used 2 use Effect: one for fetching data from backend and another for setting state.

**but getting the following exception**
1) **React Hook useEffect has a missing dependency: 'setDefaultState'. Either include it or remove the dependency array**
2) 'data' is assigned a value but never used 

Please advise on the warnings...

    useEffect(() => {
  if (!changeRequests.fulfilled) {
    dispatch(fetchRequests(), [dispatch])
  }
}, [changeRequests.fulfilled, dispatch]);

-------------
useEffect(() => {
        if (changeRequests.data) {
            setData(setDefaultState(changeRequests.data));
        }
    }, [changeRequests.data]);

【问题讨论】:

  • 请参阅How to Ask 页面。这里没有足够的信息来提供帮助。
  • OFC。请提供Minimal, Complete, and Reproducible 的尝试示例。
  • 实际上更多的是一个问题:如果我在其中一个处理程序中设置组件的状态,它可以工作,但在这里我根本无法触及任何处理程序(所有处理程序都被禁用),我该如何设置状态。
  • @DaveNewton@DrewReese 更新了代码

标签: javascript reactjs


【解决方案1】:

您可能不知道useEffect,在初始安装组件时,useEffect 可以调用 API,然后使用 useState 更改状态。如下:

import React, { useState, useEffect } from 'react';

const FormComponent = () => {
  const [data, setData] = useState(undefined);
  const [error, setError] = useState(undefined);

  useEffect(() => {
    // call an API and in the success or failure fill the data buy using setData function
    // it could be like below
    ApiCall()
      .then(response => setData(response))
      .catch(err => setError(err))
  }, []);

  ~~~

};

更新

这部分是在您添加代码之后添加的。实际上你的 dispatch 函数没有返回 Promise 事件没有返回任何东西。所以在你的代码中使用then 是不可接受的,JavaScript 解释器应该返回一个错误。我想你应该专注于你的 dispatch 函数。

【讨论】:

  • Yaa,希望返回可以在这里使用的东西......谢谢
  • 更新了 answer.solved 问题,但 gettng wasningsReact Hook useEffect 缺少依赖项:'setDefaultState'。要么包含它,要么移除依赖数组
  • 亲爱的@Roy,你得到你的答案了吗?
  • 1) React Hook useEffect 缺少依赖项:'setDefaultState'。要么包含它,要么移除依赖数组 2) 'data' 被赋值但从不使用。
  • 请提供任何建议
【解决方案2】:

为此,您需要使用 useEffect 和 useState Hooks。

  useEffect(() => {

     // write any code that will execute at first time

  }, []);  <-- [] is the empty dependency. 

在下面的示例中,LoadUser() 函数在 useEffect 中被调用,该函数将从 api 获取数据。调用成功后,使用 setPosts (useState Hook)

将响应数据设置为状态
import React, { useEffect, useState } from "react";
import axios from "axios";

function ExamplePost() {
  const [isLoading, setIsLoading] = useState(false);
  const [posts, setPosts] = useState([]);
  const [error, setError] = useState("");

  useEffect(() => {
    LoadUser();
  }, []);

  function LoadUser() {
    try {
      setIsLoading(true);
      const response = axios.get(`https://jsonplaceholder.typicode.com/posts`, {
        cancelToken: this.signal.token
      });
      response
        .then((response) => {
          setPosts(response);
          setIsLoading(false);
        })
        .catch((error) => {
          setError(error);
          setIsLoading(false);
        });
    } catch (error) {
      setIsLoading(false);
    }
  }

  return (
    <div>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>{post.title}</li>
        ))}
      </ul>
    </div>
  );
}
export default ExamplePost;

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 2021-04-17
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2017-10-23
    • 2020-08-23
    相关资源
    最近更新 更多