如何访问React Component中的变量?在Component之外初始化它

时间:2018-04-03 01:34:51

标签: javascript arrays json reactjs object

我目前是React / Redux项目的初学者。我试图从API文件中调用JSON,将其保存为对象数组,然后将其传递到另一个文件以开始从中提取数据。我最近被困在一个地方

下面是我的类,它正在访问JSON数据并将其拉出以放入数组中。我在类之外初始化了数组,但它没有被写入。我真的不确定如何扔掉'我班上需要的数组。

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"
    }
]

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

如何访问JSONproduct数组?或者,我如何弹出&#39;它离开这堂课所以我可以用它吗?

更新:使用Rahamin建议的解决方案。现在我有以下代码,全部包含在&#34; Hue&#34;类。但我仍然遇到错误。

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

2 个答案:

答案 0 :(得分:0)

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

}

答案 1 :(得分:0)

我真的不明白为什么你要把类的OUTSIDE放在一个类中,但我认为你需要了解在React中调用每个事件的时间。

componentDidMount是在所有组件都已安装到类中时调用的事件。所以在这个阶段,render()函数已经运行了。这意味着您的productJSON在此阶段尚未定义。您真正想要做的是确保在状态更新为undefined以外的其他内容时更改组件。

请尝试以下代码。

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

鉴于您确实从通话中获得了有效的colorArray,这将有效。