REACT-ROUTER-DOM渲染道具不返回任何组件

我在这里使用的是REACT-ROUTER-DOM版本6.0.2,而&Render";道具不起作用,每次我到达路径标签路径中提到的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;

jsx

Route组件推荐答案从版本5到版本6有很大变化,不是componentrender道具,而是传递给jsx文字而不是对反应组件(通过component)或函数(viarender)的引用的单一道具。

也不再有路线道具(historylocationmatch),它们只能通过Reaction挂钩访问。此外,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>
  );
};

相关文章