【问题标题】:React-router-dom Render props isn't returning any componentReact-router-dom 渲染道具没有返回任何组件
【发布时间】:2022-01-12 19:43:11
【问题描述】:

我在这里使用 react-router-dom 版本 6.0.2 并且“渲染”道具不起作用,每次我到达我的 Route 标签的路径中提到的 url 时,它总是向我抛出这个错误 - “位置“/addRecipe”的匹配叶路由没有元素。这意味着默认情况下它将呈现一个空值,从而导致一个“空”页面。”。有人可以帮我解决这个问题吗

import './App.css';
import Home from './components/Home';
import AddRecipe from './components/AddRecipe';
import items from './data';
import React, { useState } from 'react';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom';

const App = () => {
  const [itemsList, setItemsList] = useState(items)
  const addRecipe = (recipeToAdd) => {
    setItemsList(itemsList.concat([recipeToAdd]));
  }
  const removeItem = (itemToRemove) => {
    setItemsList(itemsList.filter(a => a!== itemToRemove))
  }
  return (
    <Router>
      <Routes>
        <Route path="/addRecipe" render={ ({history}) => {
          return (<AddRecipe onAddRecipe={(newRecipe) => {
            addRecipe(newRecipe);
            history.push('/');
          } }  />);
        } } />
        </Routes>
    </Router>
  );
}

export default App;

【问题讨论】:

  • 您是否正确导出AddRecipe.js 中的组件类/函数?因为我的猜测是在您发布的脚本中,AddRecipe 为空。错误消息只是由此产生的后果。

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


【解决方案1】:

Route 组件 API 从版本 5 到版本 6 发生了显着变化,而不是 componentrender 道具有一个单一的 element 道具,它被传递一个 JSX 文字而不是对 React 组件的引用(通过component)或函数(通过render)。

也不再有路由道具(historylocationmatch),它们只能通过 React 钩子访问。在此 RRDv6 之上也不再直接显示 history 对象,而是将其抽象为 navigate 函数,可通过 useNavigate 钩子访问。如果AddRecipe 组件是一个函数组件,它应该直接从钩子中访问navigate。如果它不能这样做,那么解决方案是创建一个可以的包装器组件,然后使用更正的onAddRecipe 回调呈现AddRecipe 组件。

例子:

const AddRecipeWrapper = ({ addRecipe }) => {
  const navigate = useNavigate();

  return (
    <AddRecipe
      onAddRecipe={(newRecipe) => {
        addRecipe(newRecipe);
        navigate('/');
      }}
    />
  );
};

...

const App = () => {
  const [itemsList, setItemsList] = useState(items);

  const addRecipe = (recipeToAdd) => {
    setItemsList(itemsList.concat([recipeToAdd]));
  };

  const removeItem = (itemToRemove) => {
    setItemsList(itemsList.filter(a => a !== itemToRemove))
  };

  return (
    <Router>
      <Routes>
        <Route
          path="/addRecipe"
          element={<AddRecipeWrapper addRecipe={addRecipe} />}
        />
      </Routes>
    </Router>
  );
};

【讨论】:

    【解决方案2】:

    在 react-router-dom 版本 6 中,您应该为此使用 element prop。

    我建议您阅读他们的document on upgrading from version 5,他们在其中解释了更改。

    对于你的问题,你应该这样写:

    <Route 
       path="/addRecipe" 
       element={
          <AddRecipe 
             onAddRecipe={(newRecipe) => {
               addRecipe(newRecipe);
               history.push('/');
             } 
          />
       }  
     />
    

    【讨论】:

      猜你喜欢
      • 2017-11-14
      • 1970-01-01
      • 2022-09-29
      • 2022-01-18
      • 2018-10-28
      • 2021-12-26
      • 2019-01-15
      • 2018-01-11
      • 1970-01-01
      相关资源
      最近更新 更多