首页 > 解决方案 > 如何在反应类的渲染方法中使用来自回调函数的数据

问题描述

我是 javascript 新手并做出反应,对于我的实例,我需要使用扩展类的函数xmlHttpRequest内部的数据renderreact.component

我已经使用 awindow.localstorage来保存结果并在其他地方使用它。但这看起来不像是正确的方法。

我需要的:

class MyClass extends Component {
  MyFunction() {             //the function that includes a callback function

    setInterval(function() { //the callback function

                //get some data

    }, 1000)
  }
  render() {
    return (
      <div>

      </div>
    )
  }
}

现在如何在渲染中使用这些数据?

标签: javascriptreactjs

解决方案


获取您在回调中获得的任何响应,您之前用于保存到localstorage,并将其设置为 state。

const response = res
this.setState({response})

然后在您的渲染中引用相同的内容

render(){
    return(
        <div>{this.state.response}</div>
    )
}

推荐阅读