【问题标题】:Get or save axios.get response to setState realtime when button clicked单击按钮时实时获取或保存 axios.get 对 setState 的响应
【发布时间】:2021-10-24 05:59:28
【问题描述】:

我正在开发编辑/更新功能,我想做的是在我单击表中的特定行后立即将 axios.get 的响应保存到 setState

const [dataSystem, setdataSystem] = useState([])
const [systemDetails, setsystemDetails] = ({
   ID: '',
   .....,
})

const getAllSystems = async() => {
  ......
}

const getDependentSystems = async() => { //this is being triggered by a handleselectedSysDep when a row selected
   const response = await axios.get('/API' + ID) //ID is being passed by handleselectedSysDep  from the selected row
   console.log('LIST OF SYSTEM', response.data)
   setdataSystem(response.data)
}

const [selectedSystemID, setselectedSysID] = useState('');
let selectedSysID;
const handleselectedSysDep = (ID, action) => { //will be triggered when a row selected
   setsystemDetails(ID);
   selectedSysID = {...selectedSystemID, 'ID': ID.ID}
   getDependentSystems();
}

useEffect(() => {
   getAllSystems ();
})

我想要的是当getDependentSystems() 被调用时,setdataSystem 将被立即填充以显示 API 的响应数据,因为我正在进行编辑。希望你能帮我解决这个问题。

这是console.log('LIST OF SYSTEM', response.data)的结果

谢谢

【问题讨论】:

  • 您的代码不起作用吗?你有什么问题? ID 是在哪里定义的,它是如何/何时被赋值的?
  • 我更新了我的代码@Phil,我的问题是我不能setState 实时从 API 获得的数据。我需要在单击按钮时显示它,因为我正在执行 EDIT/UPDATE 功能。谢谢
  • 如果我理解正确,您想在单击 UPDATE 按钮时调用getDependentSystems
  • 没有@Micah,请检查我提供的代码,它是 cmets

标签: reactjs axios react-hooks


【解决方案1】:

这看起来是一个很好的用例,可以使用 useEffect 挂钩来监视 systemDetails 的变化并执行您的 getDependentSystems() 副作用。

例如

const [dataSystem, setDataSystem] = useState([])
const [systemDetails, setSystemDetails] = ({
  ID: '',
  //.....,
})

const handleselectedSysDep = (ID, action) => {
  setSystemDetails(ID); // assuming `ID` is an object
}

// Now add an effect to watch for `systemDetails` changes
useEffect(() => {
  if (systemDetails.ID) {
    axios.get(`/API/${systemDetails.ID}`).then(({ data }) => setDataSystem(data))
  }
}, [ systemDetails ]) // ? note the dependencies array

您也可以使用this answer 仅在初始渲染后触发useEffect 挂钩。


仅供参考,如果您只希望 getAllSystems() 在您的组件安装时执行一次,您应该使用

useEffect(() => {
  getAllSystems()
}, []) // ? note the empty array

【讨论】:

  • 试过这个@Phil,但是在加载表时useEffect 运行,我在连接到API 时出错,因为我还没有ID 的值。我想要的是在我的初始加载表(getAllSystem)上选择一行时触发axios.get。这就是getDependentSystems被触发的时间
  • @JayDee 啊,在这种情况下,您可以在 Axios 调用周围添加条件或使用来自this answer的内容
  • @Phil 先生,它不能解决我的问题。先生,您在我的问题上遇到困难或困惑吗?让我知道您是否感到困惑。提前谢谢你
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多