reactjs REACT JS -无法将空对象的状态设置为来自API的响应

tkqqtvp1  于 2022-12-26  发布在  React
关注(0)|答案(2)|浏览(121)

我正在从我的本地API中获取json数据,但是似乎无法将其分配给err状态。

const [err, setErr] = useState({});
const host = "http://localhost:9000";

const addNote = async (obj) => {
        
  const res = await fetch(`${host}/api/notes/addnote`, {
      method : 'POST',
      headers : {'Content-Type': 'application/json', 'auth-token' : 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFiQGdtYWlsLmNvbSIsImlhdCI6MTY3MTQ0ODMyOH0.sNTvl4L9HFaGPOmuSKpJMu418axsUmgDib-94ked3lQ'},
      body : JSON.stringify(obj)
  });
  const data = await res.json();

  console.log(data);

  setErr(data);
  
  console.log(err);
}

记录数据时,我得到=〉{title:{msg :''}, description:{msg:''}}记录错误时,我得到=〉{}

omqzjyyz

omqzjyyz1#

useState()钩子是异步的,不会立即反映更新。该值在下一次呈现时得到更新,您可以使用useEffect钩子验证,如下所示

useEffect(() => {
console.log(err) // prints the updated value
}, [err])

如果希望更新立即反映出来,可以使用useRef()代替useState()。

更新答复

我不推荐使用useRef(),因为它会强制渲染之间的更新,从而影响性能。如果你想根据后端响应显示错误,那么在收到响应之前不要渲染组件。参考下面的代码片段

const [err, setErr] = useState({});
const [isDataLoading, setIsDataLoading] = useState(false);
const host = "http://localhost:9000";
const addNote = async (obj) => {
  setIsDataLoading(true); // update loading state
  const res = await fetch(`${host}/api/notes/addnote`, {
     method : 'POST',
     headers : {'Content-Type': 'application/json', 'auth-token' : 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFiQGdtYWlsLmNvbSIsImlhdCI6MTY3MTQ0ODMyOH0.sNTvl4L9HFaGPOmuSKpJMu418axsUmgDib-94ked3lQ'}, 
     body : JSON.stringify(obj)
  });
  const data = await res.json();
  setErr(data);
  setIsDataLoading(false); // update loading state
  console.log(data);
}
return (
   {
      isDataLoading ? <Loading /> : <YourComponent /> // if isDataLoading is true render some loading symbol else render your actual component.
   } 
)
tzxcd3kk

tzxcd3kk2#

const [err, setErr] = useState({});
const host = "http://localhost:9000";

const addNote = async (obj) => {
  try {
    const res = await fetch(`${host}/api/notes/addnote`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "auth-token":
          "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImFiQGdtYWlsLmNvbSIsImlhdCI6MTY3MTQ0ODMyOH0.sNTvl4L9HFaGPOmuSKpJMu418axsUmgDib-94ked3lQ",
      },
      body: JSON.stringify(obj),
    });
    const data = await res.json();
    if (res.status !== 200) {
      // need to check object and set error as per object mappig
      setErr(res.data);
    }
  } catch {
    setErr('Api not workoing');
  }

  console.log(err);
};

相关问题