简体   繁体   English

React / Redux:如何将此状态从一个组件传递到另一个文件?

[英]React/Redux: How can I pass this state from one component to another file?

I'm a beginner in React and Redux. 我是React和Redux的初学者。 I've been working on this project where I finally figured out how to store an array as a state. 我一直在从事这个项目,最后我弄清楚了如何将数组存储为状态。 Now, the only problem I'm having is, trying to figure out how to pass that state to another file. 现在,我唯一的问题是,试图弄清楚如何将该状态传递给另一个文件。

Here are the two files -Hue.js -ColorShop.js 这是两个文件-Hue.js -ColorShop.js

In Hue.js, I made an API and saved the contents into an array of objects called productJSON 在Hue.js中,我制作了一个API并将内容保存到称为productJSON的对象数组中

Hue.js Hue.js

class Hue extends React.Component {
    constructor() {
        super();
        this.state = {
            productJSON: []
        };
    }
    componentWillMount() {
    fetch('numberendpoint.json')
    .then(results => {
        return results.json();
    }).then(data => {
        let colorArray = [] //initialize array to receive json data
        for (let i =0; i < data.length; i++) {
            colorArray.push(data[i])

        }
    let productJSON = JSON.stringify(productArray)
        this.setState({productJSON: productJSON});
    })
    }

    render() {
      return (
        <div>
        <div className="container2">
        {this.state.productJSON}
    </div>
    </div>

)
}
}

Now, I'm trying to pass productJSON to another file in the same folder, ColorShop.js. 现在,我试图将productJSON传递到同一文件夹ColorShop.js中的另一个文件。 I need to replace _colors (which was reading from a static json file) with productJSON. 我需要用productJSON替换_colors(从静态json文件读取)。

ColorShop.js ColorShop.js

import Hue from './Hue.js'

const TIMEOUT = 100

Hue productJSON={this.state.productJSON} <---- my attempt to get it to work

export default { // I need to replace '_colors' with productJSON
  getColors: (cb, timeout) => setTimeout(() => cb(_colors), timeout || TIMEOUT),
}

I don't want to make another class in ColorShop.js, I just want to import this.state.productJSON into it, is that possible? 我不想在ColorShop.js中创建另一个类,只想将this.state.productJSON导入其中,这可能吗? Any pointers are greatly appreciated!! 任何指针,不胜感激!

Update: used the solution suggested by Rahamin. 更新:使用了Rahamin建议的解决方案。 Now I have this code below, all contained within the the "Hue" class. 现在,我将下面的代码包含在“ Hue”类中。 But I'm still getting errors. 但是我仍然遇到错误。

import React from 'react'

const TIMEOUT = 100

let productJSON;
class Hue extends React.Component {
  constructor() {
    super();
    this.state = {
      products: [],
    };
    this.getColors = this.getColors.bind(this)
  }
  componentDidMount() {
    fetch('http://tech.work.co/shopping-cart/products.json')
      .then(results => {
        return results.json();
      }).then(data => {

    let colorArray = []
    for (let i =0; i < data.length; i++) {
      colorArray.push(data[i])
      }
    console.log("jsonproduct=" + JSON.stringify(productArray))

    productJSON = JSON.stringify(colorArray)

   this.setState({productJSON: productJSON});

  });
  }

  render() {
    return (
      <div>
        <div className="container2">
          {this.state.productJSON}
        </div>
      </div>
      )
    }
}


export default {
  getColors: (cb, timeout) => setTimeout(() => cb(({ productJSON: value})), timeout || TIMEOUT), // here is where I am getting an error -- "value" is undefined. I'm not sure I was meant to put "value" there or something else...very new to React so its conventions are still foreign to me.
}

What do you want to do? 你想让我做什么? If the 'other file' is a helper function, you can just pass it a parameter, as you do in any function in any programming language: 如果“其他文件”是一个辅助函数,则可以像使用任何编程语言在任何函数中一样向其传递参数:

From Hue you call colorShop(productsJson) and get back a result that you can render in Hue ( colorShop starting with a lowercase character, otherwise React will think it is a component). 在Hue中,您调用colorShop(productsJson)并获取可以在Hue中渲染的结果( colorShop以小写字母开头,否则React会认为它是一个组件)。 It seems that the 'other file' can just be a function in the Hue.js file... 看来“其他文件”可能只是Hue.js文件中的一个函数...

ColorShop can also be a component that gets productsJson as a prop and renders it after modification. ColorShop也可以是将productsJson作为道具并在修改后进行渲染的组件。 ColorShop doesn't need to be a class, it can be a functional component. ColorShop不必是一个类,它可以是一个功能组件。 But this doesn't seem to be required by your example. 但这似乎不是您的示例所必需的。

Here is the code (not complete - see comments) after inserting colorShop as a function into the class component. 这是将colorShop作为函数插入类组件后的代码(不完整-请参见注释)。 And you can pass it a value and get a returned value, or have it set the state, whatever you like: 您可以根据需要将其传递一个值并获得一个返回值,或者将其设置为状态:

import React from 'react';

const TIMEOUT = 100;

class Hue extends React.Component {

  constructor() {
    super();
    this.state = {
        productJSON: []
    };
    this.getColors = this.getColors.bind(this);
  }
  componentWillMount() {
    fetch('numberendpoint.json')
      .then(results => {
          return results.json();
      }).then(data => {
          let colorArray = []; //initialize array to receive json data
          for (let i = 0; i < data.length; i++) {
            colorArray.push(data[i]);
          }
      let productJSON = JSON.stringify(productArray);
          this.setState({ productJSON: productJSON });
      });
    }

    render() {

      // call getColor from wherver you need to call it.
      // for example:
      // getColors();

      return (
        <div>
          <div className="container2">
            {this.state.productJSON}
          </div>
        </div>
      );
    }

  getColors(cb, timeout) {
    setTimeout(() => cb(colors), timeout || TIMEOUT);

    // Here you can setState({ productJSON: value });
    // Or you can return a value to the caller
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何使用带有 redux 和 react.js 的按钮将数据从一个组件传递到另一个组件? - How can i pass the data from one Component to another using a button with redux and react.js? 我如何从另一个 React 组件访问 redux 状态? - How do i access redux state from another react component? 如何将 state 从一个组件传递到另一个组件,如何修改 state? - How can I pass the state from one component to another and how can I modify the state? React - 如何将 API 数据从一个组件传递到另一个 js 文件中的另一个组件? - React - How can I pass API data from one component to another in a different js file? 如何在React js中将状态从一个组件传递到另一个组件? - How to pass state from one component to another in React js? 如何在反应 class 组件中设置另一个 state 以将数据从初始 state 传递到 - How can I set another state to pass data to from the initial state in a react class component 如何从一个组件传递 state 以设置另一个 state? - How can I pass state from one component to set another state? 如何在没有 Redux 的情况下将 props 从一个组件传递到另一个组件 - How can I pass props from one component to another withour Redux 如何将 state 从一条反应路线传递到另一条反应路线? - How can i pass a state from one react route to another react route? 如何将值从一个组件传递到另一个组件? - How can I pass values from one component to another component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM