【问题标题】:Calling a react hook again after a function is executed / inside a function (ReactJS) [duplicate]在函数执行后/在函数内部(ReactJS)再次调用反应钩子[重复]
【发布时间】:2020-05-25 19:23:43
【问题描述】:

我是反应钩子的新手,我创建了一个反应钩子函数,它从 API 接收一些数据,这些数据显示在我的页面上:

function useJobs () {
  const [jobs, setJobs] = React.useState([])
  const [locations, setLocations] = React.useState({})
  const [departments, setDepartments] = React.useState({})
  const [tags, setTags] = React.useState({})

  React.useEffect(() => {
    fetchJSON('/api/jobs/list-jobs', { headers: headers })
      .then(setJobs)
  }, [])
  React.useEffect(() => {
......

这里我有一个删除功能,它在按下按钮后执行,它会删除我列表中的项目。

function DeleteJob (jobid) {
  console.log('deletejob fired')
  console.log(jobid)
  axios({
    method: 'delete',
    url: '/api/jobs/delete-job/' + jobid,
    headers: headers
  })
  useJobs()
}

.....

<IconButton aria-label='delete' style={{ color: 'red' }} variant='outlined' onClick={() => DeleteJob(job.id)}>
     <DeleteIcon />
</IconButton>

但问题是,该项目被删除但我的显示没有得到更新;所以为了做到这一点,我在上面的函数中再次调用了useJobs() 钩子,以便在删除后更新我的显示;但我收到错误说我违反了一些反应钩子规则。如何正确更新我的页面?

【问题讨论】:

  • 您需要从钩子声明中调用 setter 函数(例如 setJobs)来更新状态。除非您更新状态,否则显示不会更新。
  • 为什么投反对票? oO

标签: javascript reactjs function react-hooks


【解决方案1】:

在 deleteJob 函数中,您应该执行以下操作:

    function DeleteJob (jobid) {
      console.log('deletejob fired')
      console.log(jobid)
      axios({
        method: 'delete',
        url: '/api/jobs/delete-job/' + jobid,
        headers: headers
      }).then(job => {
    // I am assuming your '/api/jobs/delete-job/' + jobid 
    //returns back the deleted job

    // since jobs is an array, you can filter the array and //update the state back with setJobs

    setJobs(jobs.filter(value => value.id != job.id));
            });
// If '/api/jobs/delete-job/' + jobid 
    //does not returns back the deleted job use
setJobs(jobs.filter(value => value.id != jobid));
        }

    .....

    <IconButton aria-label='delete' style={{ color: 'red' }} variant='outlined' onClick={() => DeleteJob(job.id)}>
         <DeleteIcon />
    </IconButton>

这应该可以正常工作

【讨论】:

  • no '/api/jobs/delete-job/' + jobid 不返回任何内容
  • 然后使用函数中传入的jobId
猜你喜欢
  • 2020-09-12
  • 1970-01-01
  • 2021-05-26
  • 2021-10-18
  • 2021-09-29
  • 1970-01-01
  • 2023-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多