javascript - 在每个页面上将 <Link> 与 React Router 一起使用时,Props 始终未定义

标签 javascript node.js reactjs

我正在使用react-router-domLink为了将 props 传递给其他组件,我打算在我的 /details 上使用这些 props路线。但是我似乎无法定义 Prop ,我检查了其他问题并且正在使用: <Link to={{pathname:'/details', state: {Obj:this.state}}}>无济于事:

Home.js

// this will be the home page that lists all the available leads

import React from 'react'
import {getAllLeads, getAllLeadsGraphQL} from '../../src/calls'
import List from './List'
import {LeadDetails} from './LeadDetails'
import {CreateLead} from './CreateLead'
import util from 'util'
import { BrowserRouter, Route, Switch, Link } from 'react-router-dom';


class Home extends React.Component {
  constructor(props){

  super(props)
  this.state = {
    dataType: "", // store the type of data for the type of operation that should be sent to the backend. For example "create" will have the data for creating data
    data: {},
    displayOptions: false,
    leads: [],
    selectedLead: null
    } 

    // have CRUD options that are displayed when user clicks on a lead. When on of the options are selected
    // display the appropriate fields
    this.handleChange = this.handleChange.bind(this)
    this.displayDetails = this.displayDetails.bind(this)
  }

  async handleChange(event){
    event.preventDefault()
    // use console.log here otherwise it won't show the desired value for state on the first click
    // this.setState({displayOptions: true}, () => console.log(this.state)) 
    // now get the details for each lead from backend

  }


  async displayDetails(dataType, selectedLead){
    selectedLead.contacted = JSON.stringify(selectedLead.contacted)
    this.setState({
      displayOptions: true,
      dataType: dataType,
      selectedLead: selectedLead
    }, () => console.log("options", this.state));

  };


  async componentDidMount() {
    var leads = await getAllLeads((data) => {return data});
    leads = JSON.parse(leads)
    this.setState({ leads });
    console.log("REF", leads)

    // GraphQL CALL
    // var leads = await getAllLeadsGraphQL(function(data){
    //   return data
    // })
    // leads = JSON.parse(leads)
    // leads = leads.all_leads
    // this.setState({ leads })
  }



  // <HomePage dataState={this.state}/>
  // then if the dataType isn't empty display the HTML for those fields
  // <Card Obj={this.state} displayDetails={this.displayDetails}/>
  render() {
    // when one of the leads is clicked, display options
    if(this.state.dataType === "detail" && this.state.displayOptions === true){
        console.log("DISPLAY Details",this.state.displayOptions)
        // Switch>
        // <Route path="/leads" component={Home}></Route>
        // </Switch>
        return (
          <div className="App">
            <h1> Details for {this.state.selectedLead["firstName"]}  {this.state.selectedLead["lastName"]} </h1>
            <LeadDetails Obj={this.state} />
          </div>
        )

    }
    return (
        <div className="App">
          <h1> Select lead  </h1>
            <List Obj={this.state} displayDetails={this.displayDetails}/>      
          <CreateLead/>
        </div>
      )
  }
}

export default Home;

List.js>

import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';

    class List extends Component {
      constructor(props) {
        super(props);

        this.state = {
          showMenu: false,
        };

        this.showMenu = this.showMenu.bind(this);
        this.closeMenu = this.closeMenu.bind(this);
      }

    showMenu(leadObj){
        //event.preventDefault();
        console.log("SELECTED", leadObj)
        this.props.displayDetails('detail', leadObj)

    }

      closeMenu(event) {

        if (!this.dropdownMenu.contains(event.target)) {

          this.setState({ showMenu: false }, () => {
            document.removeEventListener('click', this.closeMenu);
          }); 

        }
      }

      handleClick(arg){
          console.log("HEREw", arg)
          this.props.updateOptions(arg)
          console.log(this.props.Obj)
      }

      render() {
        console.log("THIS PROPS HERE", this.props)
        return (  
          <div>
            {this.props.Obj.leads.map(lead => (
            <div>
<Link to={{pathname:'/details', state: {Obj:this.state}}}>
            <button key={lead.id} href={lead.first_name} onClick={()=>this.showMenu({"email":lead.email, "firstName":lead.first_name, 
            "lastName":lead.last_name, "contacted": lead.contacted, "updatedAt":lead.updated_At, "createdAt": lead.created_At})}>
                {lead.first_name} {lead.last_name} 
            </button>
</Link>
            </div>  
            ))}

          </div>
        );
      }
    }


    export default List

App.js

import React from 'react'
import Home from './components/Home'
import List from './components/List'
import {CreateLead} from './components/CreateLead'
import { BrowserRouter, Route, Switch } from 'react-router-dom';

class App extends React.Component {
  render() {
    return (

      <div className="App">
        <Switch>
          <Route path="/home" component={Home}/>
          <Route path="/details" component={List} />
          <Route path="/create" component={CreateLead} />
        </Switch>
      </div>

    )
  }
}
export default App;

我可以通过location看到路线对象或其他任何东西。 , history等等

最佳答案

您可以从<Link />获取数据通过将对象传递给子组件中的属性和访问权限来组件。

<Link to={{ pathname: '/details', state: { Check: true } }}>
  <Card />
<Link>

现在您可以访问详细信息组件中的状态对象值。

const { Check } = this.props.location.state;

const Check = this.props.location.state.Check;

您可以将状态对象中的任何数据存储在子组件中并进行访问。 您甚至可以在这样的状态下 paas 对象。

 <Link to={{ pathname: '/details', state: { User: { name: 'abc' } } }}>
  <Card />
 <Link>

和访问

const userName = this.props.location.state.User.name;

查看官方文档 https://reacttraining.com/react-router/web/api/Link

关于javascript - 在每个页面上将 <Link> 与 React Router 一起使用时,Props 始终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60907194/

相关文章:

javascript - 从 Node.js 文件中获取数据并将其显示在 HTML/JS 页面中

javascript - process.env.PORT 打印奇怪的字符串

node.js - 无法加载在 'flowtype' : Cannot find module 'package.json » eslint-config-react-app' 中声明的插件 'eslint/use-at-your-own-risk' 中的 npm 错误

javascript - 如何在 react 中创建更多状态? react 状态的属性数量是否固定?

javascript - 在网页上拖动滚动

javascript - 打开没有选项卡部分的新弹出式 chrome 窗口

javascript - DOM 属性和 React

javascript - Angular 6 : control data sharing inside application

node.js - express 4 : Storing db instance

javascript - 来自reactjs-popup的弹出窗口的自定义样式