从父母到孩子反应通行证

时间:2019-04-20 07:48:23

标签: javascript reactjs

我正在尝试将React中的数据从父级传递到子级,我已经设法将正确的值从一个文件传递给另一个文件,但是同样,我传递的信息也需要再次传递。我将向您展示一些代码,以便您可以了解实际问题。

我从List.js文件中获取正确的信息,例如

<Products categoryid={item.id}/>

所以我将相同的item.id传递给了产品,如您所见,我有this.props.categoryid,它为我提供了正确的信息,作为添加该产品的价值,看起来像

import React, { Component } from 'react'
import { getProducts, addItem, deleteItem, updateItem } from './ProductFunctions'


class Products extends Component {
    constructor() {
        super()
        this.state = {
            id: '',
            title: '',
            price: '',
            off_price: '',
            category_id: '',
            arttitle: '',
            artbody: '',
            editDisabled: false,
            items: []
        }
this.onSubmit = this.onSubmit.bind(this)
        this.onChange = this.onChange.bind(this)
    }

    componentDidMount() {
        this.getAll()
    }

    onChange = e => {
        this.setState({
            [e.target.name]: e.target.value

        })
    }

    getAll = () => {
        getProducts().then(data => {
            this.setState(
                {
                    title: '',
                    price: '',
                    off_price: '',
                    category_id: this.props.categoryid,
                    items: [...data]
                },
                () => {
                    console.log(this.state.items)
                }
            )
        })
    }

所以真正的问题是如何将this.props.categoryid作为category_id传递给ProductFunctions.js中的getProducts函数,这样我才能从中获取列表?

export const getProducts = category_id => {
    return axios
        .get('/api/products/${category_id}', {
            headers: { 'Content-Type': 'application/json' }
        })
        .then(res => {
            return res.data
        })
}

2 个答案:

答案 0 :(得分:1)

看来您忘记了在getProducts的{​​{1}}函数中使用``而不是使用'',所以让我们更正这一点。

ProductFunctions.js

现在,在调用时,只需将export const getProducts = category_id => { return axios .get(`/api/products/${category_id}`, { headers: { "Content-Type": "application/json" } }) .then(res => { return res.data; }); }; 方法中从categoryid获得的props传递给getProducts。 (根据导出的功能在getAll

中的期望
ProductFunctions.js

答案 1 :(得分:0)

getAll函数中访问道具

getAll = () => {
  getProducts(this.props.categoryid).then(data => {
    this.setState({
        title: '',
        price: '',
        off_price: '',
        category_id: this.props.categoryid,
        items: [...data]
      },
      () => {
        console.log(this.state.items)
      }
    )
  })
}