通过Link传递道具时this.props.location未定义

时间:2020-03-25 15:06:17

标签: javascript reactjs react-router

在这里反应初学者,再次陷入困境。通过多个组件传递道具时,出现this.props.location未定义错误。我将道具添加到Link组件,然后将它们传递到Route组件,然后再次将它们传递到Link输出组件。

列表/链接组件

import React from "react";
import "./ProductList.css";
import {Link} from "react-router-dom";

class ProductList extends React.Component {
    render() { 
        const products = this.props.products;
        return (
            <div>
                <h1>Product List</h1>
                <table>
                    <tr>
                        <th>Name</th>
                        <th>EAN Code</th>
                        <th>Type</th>
                        <th>Weight</th>
                        <th>Color</th>
                        <th>Active</th>
                    </tr>
                    {products.map((product, index) => {
                        return (
                            <tr key={index}>
                                <td>{product.name}</td>
                                <td>{product.ean}</td>
                                <td>{product.type}</td>
                                <td>{product.weight}</td>
                                <td>{product.color}</td>
                                <td><input type="checkbox" checked={product.active} onChange={(e) => this.props.setProductActive(product, e.target.checked)} /></td>
                                <td><Link to={{ pathname: "/view", prodIndex: {index}}} ><button>View</button></Link></td>
                                <td><button>Edit</button></td>
                                <td><button onClick={() => this.props.deleteProduct(index)}>Delete</button></td>
                            </tr>
                        )
                    })}
                </table>
            </div>
        )
    }
}
export default ProductList;

“应用程序/路由”组件

import React from 'react';
import './App.css';
import ProductList from "../ProductList/ProductList";
import NewProd from "../NewProd/NewProd";
import ViewProd from "../ViewProd/ViewProd";
import {BrowserRouter, Route} from "react-router-dom";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
            name: "", 
            ean: "", 
            type: "", 
            weight: "", 
            color: "", 
            active: false,
            products: [{name: "Cabbage", ean: "00000000", type: "Vegetable", weight: "2kg", color: "Green", active: false}, 
            {name: "Banana", ean: "111111111", type: "Fruit", weight: "0.3kg", color: "Yellow", active: false}, 
            {name: "Chocolate", ean: "22222222222", type: "Candy", weight: "0.2kg", color: "Brown", active: false}, 
            {name: "Orange", ean: "3333333333", type: "Fruit", weight: "0.5kg", color: "Orange", active: false}, 
            {name: "Cucumber", ean: "4444444444", type: "Vegetable", weight: "1kg", color: "Green", active: false}, ]
    };
};

handleFormSubmit = (e) => {
  e.preventDefault();
  let products = [...this.state.products];

  products.push({
      name: this.state.name,
      ean: this.state.ean,
      type: this.state.type,
      weight: this.state.weight,
      color: this.state.color,
      active: false,
  });
  this.setState({ products, name: "", ean: "", type: "", weight: "", color: "", active: false}
  );
}
handleInputChange = (e) => {
  let input = e.target;
  let name = e.target.name;
  let value = input.value;
  this.setState({[name]: value})
  };

deleteProduct = (delIndex) => {
  let products = [...this.state.products].filter((product, index) => index !== delIndex);
  this.setState({ products });
};
isActive = () => {
  this.setState({active: !this.state.active})
}
setProductActive = (product, active) => {
  this.setState((state) => ({
    products: state.products.map(p => p.name === product.name ? { ...p, active } : p)
  }))
}
render() {
  return (
    <BrowserRouter>
    <div className="App">
      <ProductList products={this.state.products} 
      deleteProduct={this.deleteProduct}
      setProductActive={this.setProductActive} />
      <NewProd handleFormSubmit={this.handleFormSubmit}
      handleInputChange={this.handleInputChange}
      newName={this.state.name}
      newEan={this.state.ean}
      newType={this.state.type}
      newWeight={this.state.weight}
      newColor={this.state.color} />
      <Route path="/view" render={(props) => <ViewProd {...props} products={this.state.products} 
      prodIndex={this.props.location.prodIndex} />} />
    </div>
    </BrowserRouter>
  );
  }
}

export default App;

输出组件

import React from "react";
import "./ViewProd.css";

class ViewProd extends React.Component {
    render() { 
        const products = this.props.products;
        const index = this.props.prodIndex;
        return (
            <div>
                <h1>View Product</h1>
                <ul>
                    <li>{`Name: ${products[{index}].name}`}</li>
                    <li>{`EAN Code: ${products[{index}].ean}`}</li>
                    <li>{`Type: ${products[{index}].type}`}</li>
                    <li>{`Weight: ${products[{index}].weight}`}</li>
                    <li>{`Color: ${products[{index}].color}`}</li>
                    <li>{`Active: ${products[{index}].active}`}</li>
                </ul>
            </div>
        )
    }
}
export default ViewProd;

目标是,当您按下视图按钮时,它将打开带有信息列表的viewProduct组件。我正在努力显示具有特定索引的产品信息。我想将索引从ProductList组件传递到ViewProd组件,据我所知,它需要通过Link和React组件。预先感谢。

1 个答案:

答案 0 :(得分:0)

根据docs的最佳方法就是这样做。

<td><Link to={{ pathname: "/view", state: { prodIndex: {index} }}} ><button>View</button></Link></td>

然后,您无需将其通过route / app组件。使用<Route>的渲染功能渲染的组件的道具中将自动提供它。

ViewProd.js

const index = this.props.location.state.prodIndex;

从您的“应用/路由”组件中删除

prodIndex={this.props.location.prodIndex}

位置在这里不可用,由于您正在尝试访问undefined中的密钥,因此会给您一个错误。