【问题标题】:Pass parameter to page, data not updating将参数传递给页面,数据不更新
【发布时间】:2022-01-12 12:07:56
【问题描述】:

我有一个导航组件,我在其中将参数传递到另一个页面,正在传递参数,但是,下拉列表中的数据并未针对传递的 ID 进行更新:

导航:

<Link to='/service/ServiceAppointment/${car.Make}'> { serviceAppointment } </Link>

预约页面:

const ScheduleAppointment = () => {
 const { id } = useParams();
 
console.log (id);  //I can see the ID passed to the page in the console
 
  useEffect(() => {
    console.log(id); //the ID is not there
    scheduleAppointment(id);   
  });

  const Appointment= () => {
     //call to API for open dates
     //the ID never gets here

  }
}

路由器:

<Route exact path='/service/appointment/:id' component={ ScheduleAppointment }   />

当一个新的 ID 被传递给预约页面时,我怎样才能改变它?

【问题讨论】:

    标签: reactjs react-native react-hooks react-router


    【解决方案1】:

    请更新以下链接而不是您的代码

    <Link to=`/service/ServiceAppointment/${car.Make}`> { serviceAppointment } </Link>
    

    我希望它对你有用!谢谢。

    【讨论】:

    • 这就是我所拥有的,出于某种原因,${car.Make} 在页面上显示为绿色
    【解决方案2】:

    useEffect 的依赖参数是 useEffect(callback, dependencies)

    让我们探索副作用和运行:

    未提供:每次渲染后都会运行副作用。

     import { useEffect } from 'react';
        
        function MyComponent() {
          useEffect(() => {
            // Runs after EVERY rendering
          });  
        }
    

    一个空数组[]:副作用在初始渲染后运行一次。

     import { useEffect } from 'react';
        
        function MyComponent() {
          useEffect(() => {
            // Runs ONCE after initial rendering
          }, []);
        }
    

    有 props 或 state 值[prop1, prop2, ..., state1, state2]:只有在任何依赖值发生变化时才会产生副作用。

    import { useEffect, useState } from 'react';
    
    function MyComponent({ prop }) {
      const [state, setState] = useState('');
      useEffect(() => {
        // Runs ONCE after initial rendering
        // and after every rendering ONLY IF `prop` or `state` changes
      }, [prop, state]);
    }
    

    在你的情况下尝试这种方式

    useEffect(() => {
        console.log(id); //the ID is not there
        scheduleAppointment(id);   
    },[id]);
    

    【讨论】:

    • 这行得通。添加 [id] 有效,谢谢:useEffect(() => { console.log(id); //ID 不存在 scheduleAppointment(id); },[id]);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    相关资源
    最近更新 更多