【问题标题】:In React How to pass object using history.push from a component to child component and read data在 React 如何使用 history.push 从组件传递对象到子组件并读取数据
【发布时间】:2021-04-09 08:20:49
【问题描述】:

我有显示表中记录的父组件。当用户单击它时,它会重定向到使用历史推送传入参数的记录 ID 的子组件。这一切都很好,但是除了我无法实现的参数之外,我还需要传递一个数据对象,以及我在子组件中需要哪些步骤来读取这个对象?

对象定义

export interface ISearchCriteriaForm{
  startTime: string,
  endTime: string,
  liveTime?: string,
  schedAction_Active: string,
  siteId?: number,
  scheduleId?: number
}

父组件

const MyComponentA = () => {

 const [url] = useState("/eziTracker/eziStatus");
const[eziSearchCriteria, setEziSearchCriteria] = useState<ISearchCriteriaForm>();

//when row clicked on table
const selectedRow = (row: any) => { 
//history.push(`${url}/${row.siteId}`);  // this works
 
 history.push({     // this is how I am trying to achieve ??
   pathname: `${url}/${row.siteId}`,
   state: eziStatusSearchCriteria
  });
 };

子组件

const MyChildComponent = () =>{
  const match = useRouteMatch("/eziTracker/eziStatus/:id/:hash");
  const[eziStatusSearchCriteria, setEziStatusSearchCriteria] = useState<IEziStatusSearchCriteriaForm>();

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

错误

Expression expected.  TS1109

   88 |       pathname: `${url}/${row.siteId}`,
   89 |       state: eziStatusSearchCriteria
 > 90 |     });
      |     ^
   91 | };
   92 | 
   93 | const setDefaultSearchCriteria = () =>{

【问题讨论】:

  • 我认为这不是打字稿问题而不是 rect.js 错误中的问题。我认为您应该将 { // this is how I am trying to achieve ?? pathname: ${url}/${row.siteId}, state: eziStatusSearchCriteria } 状态分配给变量,并在 history.push 方法中作为 2 个语句再次调用它。喜欢,stackoverflow.com/questions/35821614/…
  • 是否要使用查询参数过滤表数据?
  • 你是对的,我已经改变了我为状态赋值的方式,它确实有效,参考我的回答

标签: reactjs react-router-dom


【解决方案1】:

通常你需要做这样的事情来实现你的目标:

首先您需要为history.push 函数创建一个location object,如下所示:

const location = {
   pathname: `${url}/${row.siteId}`,
   state: eziStatusSearchCriteria || {}
}

然后使用history.push(location) 转到您指定的location,然后在目的地中您需要做的就是一些如何访问location 对象的方法,最简单的方法是使用useLocation 钩子,如下所示:

const location = useLocation();

//NOW you can use location.state object to get your data

【讨论】:

  • @Toxic 很高兴我能帮上忙 ;)
【解决方案2】:

父组件

const selectedRow = (row: any) => { 

eziSearchCriteria.siteId = row.siteId;

history.push({
  pathname: `${url}/${row.siteId}`,
  state: {searchCriteria: eziSearchCriteria}
});
};

子组件

  let location = useLocation();

  const setSearchCriteria =() =>{
   if(location.state.searchCriteria!=null || location.state.searchCriteria !=''){
     setEziStatusSearchCriteria(location.state.searchCriteria)
   }
 }

【讨论】:

    猜你喜欢
    • 2018-11-26
    • 2018-01-01
    • 2022-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 1970-01-01
    • 2020-03-04
    相关资源
    最近更新 更多