Solution to use routing to pass state parameters in react, but props are empty

1. Introduction to the problem

Requirement: After clicking on the route to jump, you need to pass some parameters to the page you jump to.

Problem: Not only no parameters are received, but the entire props are empty

Initial code: I initially wrote two class components

2. Problem solving

2.1: After searching on the Internet, I tried many methods but none worked, and many of them were for function components.
Then I changed the component after the jump into a functional component.
2.2: Solution (useLocation):
//Code of functional component

import React from 'react'
import {
    
    useLocation} from 'react-router-dom'

function TaskDetails (){
    
    

    const location = useLocation();
    console.log(location);
  const myParam = location.state?.myParam ?? '';
  console.log(myParam);
    return (
      <div>Task details</div>
    )
  }

  export default TaskDetails

Register link code

 <Link to='/taskDetails' state={
    
    tasksObj} >  //tasksObj是一个对象

Code to register Route

 render() {
    
    
       const {
    
    userId} = this.props
       const AlinputRmin = ()=><div><TaskDetails/></div>
        return (
            <Fragment>
          
                    <Route path='/taskDetails/*'  element={
    
    AlinputRmin()}/>

                    <Route path="*" element={
    
    <Navigate to="/mainPages" />} />
                </Routes>
                
                </Fragment>
                }

3. Attention

3.1: useParams can also be solved. Since I am passing an object, I choose to use useLocation.
3.2: If you know how to directly solve the problem of passing between class components, you can share it.

Guess you like

Origin blog.csdn.net/m0_63135041/article/details/131177468