【问题标题】:How to access variable inside React Component? Initialized it outside Component如何访问 React 组件中的变量?在组件外部初始化它
【发布时间】:2018-04-03 01:34:50
【问题描述】:

我目前是一名初学者,正在研究 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 数组?或者,我如何将它从这个类中“弹出”出来以便我可以使用它?

更新:使用了 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(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)
}

【问题讨论】:

  • 需要全局访问的数据应该存储在redux状态。如果您只需要子组件中的数据,请将其作为道具传递。我强烈建议您在开始之前查看一些 redux react 教程
  • 您能解释一下为什么您认为您所尝试的方法不起作用吗?我看不到任何尝试在类之外使用 productJSON 变量的代码
  • fetch 应在componentDidMount 调用
  • 谢谢@klugjo,我学习 React-Redux 的时间很短,所以我还在学习状态。
  • @MartinBooth 你是对的,我认为我实际上并没有试图在方法之外调用它。接下来我将尝试将它传递给另一个组件,所以我们将看看它是如何进行的。

标签: javascript arrays json reactjs object


【解决方案1】:
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;
           }

}

【讨论】:

    【解决方案2】:

    我真的不明白您为什么要尝试将数组放在类之外,但我认为您需要了解每个事件何时在 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,这将起作用。

    【讨论】:

      猜你喜欢
      • 2012-07-04
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-12-25
      相关资源
      最近更新 更多