【问题标题】:React/Redux: How can I pass this state from one component to another file?React/Redux:如何将此状态从一个组件传递到另一个文件?
【发布时间】:2018-09-12 07:41:12
【问题描述】:

我是 React 和 Redux 的初学者。我一直在研究这个项目,我终于弄清楚了如何将数组存储为状态。现在,我遇到的唯一问题是,试图弄清楚如何将该状态传递给另一个文件。

这是两个文件 -Hue.js -ColorShop.js

在 Hue.js 中,我创建了一个 API 并将内容保存到一个名为 productJSON 的对象数组中

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>

)
}
}

现在,我正在尝试将 productJSON 传递到同一文件夹中的另一个文件 ColorShop.js。我需要用 productJSON 替换 _colors(从静态 json 文件中读取)。

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),
}

我不想在 ColorShop.js 中创建另一个类,我只想将 this.state.productJSON 导入其中,可以吗?任何指针都非常感谢!

更新:使用了 Rahamin 建议的解决方案。现在我在下面有这段代码,全部包含在“Hue”类中。但我仍然遇到错误。

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.
}

【问题讨论】:

  • 使用 Redux 而不是组件状态,你应该在 reducer 中声明状态并在你想要的地方全局访问它。您可以通过 store.getState(); 轻松访问状态
  • 否则你可以制作一些包装器,它会调用fetch 并存储你收到的数据,然后将它传递给它的嵌套Color 和/或Hue。常见的 React 方法 afaik。

标签: javascript reactjs api components state


【解决方案1】:

你想做什么?如果“其他文件”是一个辅助函数,您可以只传递一个参数,就像在任何编程语言的任何函数中一样:

从 Hue 调用 colorShop(productsJson) 并返回一个可以在 Hue 中渲染的结果(colorShop 以小写字符开头,否则 React 会认为它是一个组件)。看来“其他文件”只能是 Hue.js 文件中的一个函数...

ColorShop也可以是一个组件,获取productsJson作为prop,修改后渲染。 ColorShop 不需要是一个类,它可以是一个功能组件。但是您的示例似乎不需要这样做。

这是将colorShop 作为函数插入到类组件中后的代码(不完整 - 请参阅 cmets)。您可以将一个值传递给它并获得一个返回值,或者让它设置状态,随心所欲:

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
  }

【讨论】:

  • 非常感谢您的帮助!我试过你的例子,但我仍然产生一些错误。我会在上面复制它们......如果你有时间帮助我找出我做错了,我真的很感激(或者如果任何其他用户这样做)
  • 谢谢!我想知道我不能像那样传递 ({ productJSON:value }) 什么。
  • (1) 你在哪里定义productArray?我没有看到它的定义。 (2)我对这种类型的导出不熟悉......通常我导出类本身......如果你不导出它,这个类在哪里使用?这个类没有用到这两个导出的函数,为什么会出现在这里呢? (3) 什么是'cb'?
  • (1) 对不起,我刚才把它改回了 colorArray。 (2) 我只是想创建一个类,这样我就可以在一个类中进行 API 调用,所以除了这个文件之外,这个类实际上并不存在于任何地方。 3) 来自 redux 文档:中间件将执行调用 fn(...arg, cb)。 cb 是中间件传递给 fn 的回调。如果 fn 正常终止,它必须调用 cb(null, result) 来通知中间件一个成功的结果。如果 fn 遇到一些错误,那么它必须调用 cb(error) 来通知中间件发生了错误。
  • productArray 是在哪里定义的?另外,如果你不在任何地方使用这个类,你在哪里使用这里获取的数据?为什么不在使用它的组件中获取这些数据呢?你提到了redux,但我没有看到你在这里使用redux。很多问题:)
猜你喜欢
  • 1970-01-01
  • 2021-01-11
  • 2021-03-01
  • 2019-05-17
  • 2018-11-03
  • 2020-03-12
  • 2019-12-11
  • 1970-01-01
  • 2018-09-28
相关资源
最近更新 更多