简体   繁体   English

如何在React Component内部访问变量? 在组件外部初始化

[英]How to access variable inside React Component? Initialized it outside Component

I'm currently a beginner working on a project in React/Redux. 我目前是在React / Redux中从事项目工作的初学者。 I'm trying to call JSON from an API file, save it as an array of objects, and then pass it into another file to start pulling data out of it. 我正在尝试从API文件调用JSON,将其保存为对象数组,然后将其传递到另一个文件中以开始从中提取数据。 I recently got stuck in one place 我最近被困在一个地方

Below is my class, which is accessing the JSON data and pulling it out to put into an array. 下面是我的类,该类正在访问JSON数据并将其拉出放入数组。 I initialized the array outside of the class, but it's not being written to. 我在类外部初始化了数组,但未将其写入。 I'm not really sure how to 'throw' the array that I need out of my class. 我不太确定如何从课堂上“抛出”我需要的数组。

numberendpoint.json (an array of objects) numberendpoint.json(对象数组)

[
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    },
    {
        color: "magenta",
        value: "#f0f"
    },
    {
        color: "yellow",
        value: "#ff0"
    },
    {
        color: "black",
        value: "#000"
    }
]

In index.js 在index.js中

let productJSON = [] //initialize productJSON array here

class Hue extends React.Component {
    constructor() {
        super();
        this.state = {
            elements: [],
            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])
            }
            productJSON = JSON.stringify(productArray) //here is where I try to assign the productJSON array
            let elements = data.map((rainbow) => {
                return (
                    <div key={rainbow.results}>
                        <p>{raindow.color}</p>
                        <p>{rainbow.value}</p>
                    </div>
                )
            })
            this.setState({elements: elements});
            console.log("state", this.state.elements[0]);
        })
    }

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

How can I access the JSONproduct array? 如何访问JSONproduct数组? or alternatively, how do I 'pop' it out of this class so I can use it? 或者,如何从课程中“弹出”它以便使用?

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(productArray)

   this.setState({productJSON: productJSON});

  });
  }

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


export default {
  getProducts: (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.
  buyProducts: (payload, cb, timeout) => setTimeout(() => cb(), timeout || TIMEOUT)
}
let productJSON = [] //initialize productJSON array here

class Hue extends React.Component {
    constructor() {
        super();
        this.state = {
            elements: [],
            productJSON: []
        };
    }

    componentDidMount() {
        fetch('numberendpoint.json')
        .then(res => {
            this.setState({elements: res.data});
        })
    }

render() {
            if(this.state.elements.length > 0){ //once the data is fetched
              return (
                <div>
                <div className="container2">
                {this.state.elements.map((rainbow) => {
                return (
                    <div key={rainbow.results}>
                        <p>{raindow.color}</p>
                        <p>{rainbow.value}</p>
                    </div>
                )
            })}
            </div>
            </div>
        )
            }
           else{ // initial render
             return null;
           }

}

I don't really understand why you are trying to put array OUTSIDE of a class but I think you need to understand when each event gets called in React. 我真的不明白为什么您要尝试将一个类的数组放到外面,但是我认为您需要了解何时在React中调用每个事件。

componentDidMount is an event that gets called when all the components have mounted in the class. componentDidMount是一个事件,当所有组件都安装在类中时会被调用。 So at this stage, render() function has already run. 因此,在此阶段, render()函数已经运行。 Which means your productJSON is undefined at this stage. 这意味着您的productJSON在此阶段未定义。 What you really wanna do is that make sure your component changes when the state gets updated to something other than undefined . 您真正想做的是确保在状态更新为undefined其他内容时更改组件。

Try the following code. 请尝试以下代码。

let productJSON = [] //initialize productJSON array here

class Hue extends React.Component {
    constructor() {
        super();
        this.state = {
            elements: [],
        };
    }

    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])
            }
            this.setState({productJSON:colorArray});

            let elements = data.map((rainbow) => {
                return (
                    <div key={rainbow.results}>
                        <p>{raindow.color}</p>
                        <p>{rainbow.value}</p>
                    </div>
                )
            })
            this.setState({elements: elements});
            console.log("state", this.state.elements[0]);
        })
    }

    render() {
        return (
            <div>
            <div className="container2">
            {this.state.productJSON ? 'state not ready' : this.state.productJSON} //this is the important part. It will render this.state.productJSON only when it is a truthy value.
        </div>
        </div>
    )}
}

Given that you do get a valid colorArray from your call, this will work. 假设您确实从调用中获得了一个有效的colorArray ,那么它将起作用。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM