通过React Router Render传递的道具在Component中未定义

时间:2020-11-10 11:45:47

标签: javascript reactjs

我正在尝试通过Route将数据从状态传递到组件。我已经使用了渲染api将道具传递给组件。但是道具来的不确定!这是代码。

import React, { Component } from "react";
import SummaryPage from "../../Layout/SummaryPage/SummaryPage";
import { Route } from "react-router-dom";
import ContactData from "./ContactData/ContactData";

class Checkout extends Component {
  state = {
    ingredients: null,
    price: 0,
  };

  // Parse the query Params when the component is mounted
  componentWillMount() {
    // Getting the query
    const query = new URLSearchParams(this.props.location.search);

    // Ingredients as an empty object
    let ingredients = {};
    let price = 0;

    // Looping through the query entries and setting ingredient's value and key to the object
    for (let param of query.entries()) {
      if (param[0] === "price") {
        price = param[1];
      } else {
        ingredients[param[0]] = +param[1];
      }
    }

    // Updating the state
    this.setState({ ingredients: ingredients, totalPrice: price });
  }

  // Cancel checkout and go back to builder
  checkoutCancelledHandler = () => {
    this.props.history.goBack();
  };

  checkoutContinuedHandler = () => {
    this.props.history.replace("/checkout/contact-data");
  };

  render() {
    return (
      <div>
        {/* SummaryPage */}
        <SummaryPage
          ingredients={this.state.ingredients}
          checkoutCancelled={this.checkoutCancelledHandler}
          checkoutContinued={this.checkoutContinuedHandler}
        />

        <Route
          path={this.props.match.path + "/contact-data"}
          render={(props) => (
            <ContactData
              {...props}
              ingredients={this.state.ingredients}
              price={this.state.totalPrice}
            />
          )}
        />
      </div>
    );
  }
}

export default Checkout;

我尝试了所有可能的解决方案,但是没有用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为您错误地访问了查询字符串。您需要从全局 document 对象访问您的搜索参数。

尝试:

['Matrix_spike_2_D1_1', 'Matrix_spike_4_D1_1']

然后您可以像这样访问参数:

ls = [1.1, 2.0, 3.0, 4.0, 5.0]
files = ['a', 'b', 'Matrix_spike_2_D1_1', 'c', 'Matrix_spike_4_D1_1']
sought_files = {f'Matrix_spike_{int(x)}_D1_1' for x in ls if x.is_integer()}
matched_files = list(filter(lambda f: f in sought_files, files))
print(matched_files)

const query = new URLSearchParams(document.location.search);

此处有更多详细信息: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams