状态未传递给子组件

时间:2020-06-08 15:53:15

标签: javascript reactjs

在确定道具没有被树传下来的条件时,我遇到了一个问题。我有一个Fetcher类,在其中填充“布局”,然后将其传递给子项props,但是我不能从子组件中访问它。

EX:

   import React, { Component } from 'react'
   import axios from "axios";

    export default class Fetcher extends Component {

constructor(props) {
    super(props)
    this.state = {
        layouts: [],
}

componentDidMount() {
    this.getLayouts();
}

getLayouts = () => {
    axios
        .get("/layout")
        .then((res) => {
            this.setState({
                layouts: res.data,
            });
        })
        .catch((err) => console.log(err));
};

render() {
    return (

        this.props.children(this.state.layouts)
    )
}

}

这是我的“父母”组件,上面传递了一些道具孩子:

例如:

 import React, { Fragment } from "react";
 import Fetcher from "./Fetcher";

 class App extends Component {

          <Fetcher>
            {(layouts) => {
              return <Fragment>
                <NewLayout
                  layoutsList={layouts} />
              </Fragment>
            }}
          </Fetcher>
 }







 import React from "react";



 class NewLayout extends React.Component {


 constructor(props) {
  super(props)
  this.state = {

  layouts: [],
  }}

 componentDidMount() {
  this.setState(() => ({
    layouts: this.props.layoutList
  }))
 }


   render() {

  { console.log(this.state.layouts) }
  { console.log(this.props.layoutList) }


  return (
   ....

2 个答案:

答案 0 :(得分:0)

children prop is not a function,如果要将属性传递给它,则应将React.Children API与React.cloneElement一起使用:

add_action( 'woocommerce_after_add_to_cart_form', 'total_product_and_subotal_price' );
function total_product_and_subotal_price() {
    global $product;
    // the div section
    echo sprintf('',__('Product Total:','woocommerce'),''.$product->get_price().'');
    echo sprintf('',__('Cart Total:','woocommerce'),''.$product->get_price().'');
    ?>
        <script>
            jQuery(function($){
                var price = get_price(); ?>,
                    current_cart_total = cart->cart_contents_total; ?>,
                    currency = '';
                $('[name=quantity]').change(function(){
                    if (!(this.value < 1)) {
                        var product_total = parseFloat(price * this.value),
                        cart_total = parseFloat(product_total + current_cart_total);
                        $('#product_total_price .price').html( currency + product_total.toFixed(2));
                        $('#cart_total_price .price').html( currency + cart_total.toFixed(2));
                    }
                    $('#product_total_price,#cart_total_price').toggle(!(this.value <= 1));
                });
            });
        </script>
    <?php
}

答案 1 :(得分:0)

我的朋友错字了,好像您将layoutsList属性传递给NewLayout,但在内部使用layoutList