【问题标题】:react-router-dom v6 useNavigate passing value to another componentreact-router-dom v6 useNavigate 将值传递给另一个组件
【发布时间】:2020-10-28 04:20:55
【问题描述】:

react-router-dom 的版本是 v6,我无法使用 Navigate 将值传递给另一个组件。

我想将选定的行传递到另一个名为 Report 的页面。但是,我不确定我为 navigate 方法使用了正确的语法,而且我不知道如何在 Report 组件中获取该状态。

Material-ui 表:我正在尝试在onClick 参数中使用redirectToReport(rowData)

function TableRows(props){
return (
    <MaterialTable
        title="Leads"
        columns={[
            ...
        ]}
        data = {props.leads}       
        options={{
            selection: true,
            filtering: true,
            sorting: true
        }}
        actions = {[{
            position: "toolbarOnSelect",
            tooltip: 'Generate a report based on selected leads.',
            icon: 'addchart',
            onClick: (event, rowData) => {
                console.log("Row Data: " , rowData)
                props.redirect(rowData)
            }
        }]}
    />
)}

LeadTable 组件

export default function LeadTable(props) {
let navigate = useNavigate();

const [leads, setLeads] = useState([]);
const [loading, setLoading] = useState(true);    

async function fetchUrl(url) {
    const response = await fetch(url);
    const json = await response.json();

    setLeads(json[0]);
    setLoading(false);
}

useEffect(() => {
    fetchUrl("http://localhost:5000/api/leads");
}, []);

function redirectToReport(rowData) {
    navigate('/app/report', { state: rowData }); // ??? I'm not sure if this is the right way
}

return(
    <div>
        <TableRows leads={leads} redirect={redirectToReport}></TableRows>
    </div>
)}

报表组件

export default function ReportPage(state) {
return (
    <div>
        { console.log(state) // This doesn't show anything. How to use the state that were passed from Table component here?}
        <div className = "Top3">
          <h3>Top 3 Leads</h3>
            <ReportTop3 leads={[]} />
        </div>
    </div>
);}

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    您的 navigate('/app/report', { state: rowData }); 对我来说是正确的。

    react-router-v6

    如果需要状态,请使用navigate('success', { state })

    您的ReportPage 需要在执行推送的组件所在的Router 下呈现。

    Route props 不再传递给渲染组件,因为它们现在作为 JSX 文字传递。要访问路由状态,必须通过 useLocation 挂钩。

    function ReportPage(props) {
      const { state } = useLocation();
      console.log(state);
    
      return (
        <div>
          <div className = "Top3">
            <h3>Top 3 Leads</h3>
              <ReportTop3 leads={[]} />
          </div>
        </div>
      );
    }
    

    如果组件不能使用 React 钩子,那么您仍然可以通过自定义 withRouter 高阶组件访问路由状态。这是一个简单的withRouter HOC 示例,用于将location 作为道具传递。

    const withRouter = WrappedComponent => props => {
      const location = useLocation();
    
      return <WrappedComponent {...props} location={location} />;
    };
    

    然后像在 RRDv6 之前所做的那样通过 props 访问。

    function ReportPage(props) {
      console.log(props.location.state);
    
      return (
        <div>
          <div className = "Top3">
            <h3>Top 3 Leads</h3>
              <ReportTop3 leads={[]} />
          </div>
        </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      第 6 版 react-router-dom

      我知道问题已得到解答,但我觉得这对于那些想要使用功能组件并且正在使用 react-router-dom v6 在组件之间传递数据的人来说可能是一个有用的示例。

      假设我们有两个功能组件,第一个组件 A,第二个组件 B。组件 A 想要与组件 B 共享数据。

      钩子的使用: (useLocation,useNavigate)


      import {Link, useNavigate} from 'react-router-dom';
      
      function ComponentA(props) {
      
        const navigate = useNavigate();
      
        const toComponentB=()=>{
      navigate('/componentB',{state:{id:1,name:'sabaoon'}});
        }
      
        return (
         <>
      <div> <a onClick={()=>{toComponentB()}}>Component B<a/></div>
      </>
        );
      
      
      }
      
      
      export default ComponentA;
      

      现在我们将获取组件 B 中的数据。

      import {useLocation} from 'react-router-dom';
      
       function ComponentB() {
      
          const location = useLocation();
         
              return (
      
                  <>
                     
      <div>{location.state.name}</div>
      
                  </>
              )
          }
      
      export default ComponentB;
      

      注意:如果您使用类组件,则可以使用 HOC,因为钩子在类组件中不起作用。

      【讨论】:

        【解决方案3】:

        2 件事(只是一个建议): 而不是三元使用 &&

        {location && <div>{location.state.name}</div>}
        

        为什么要检查位置并渲染 location.state.name?我会检查您正在获取的数据或确保数据返回 null 或您的值。

        【讨论】:

          【解决方案4】:

          Sabaoon Bedar的答案中,您可以在显示之前检查是否有任何数据:

          • 而不是这个&lt;div&gt;{location.state.name}&lt;/div&gt;

          • 这样做{ location != null ? &lt;div&gt;{location.state.name}&lt;/div&gt; : ""}

          【讨论】:

            猜你喜欢
            • 2022-07-07
            • 2022-08-23
            • 2022-12-25
            • 2021-07-13
            • 2017-09-14
            • 2022-01-06
            • 2021-04-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多