如何在React类的render方法中使用来自回调函数的数据

时间:2019-04-17 09:49:46

标签: javascript reactjs

我是JavaScript的新手,因此我需要使用扩展xmlHttpRequest

的类的render函数中的react.component数据

我已使用window.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>
    )
  }
}

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

3 个答案:

答案 0 :(得分:0)

接受您先前在回调中保存到localstorage的任何响应,并将其设置为状态。

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

然后在渲染器中引用相同的图片

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

答案 1 :(得分:0)

在课堂上使用状态

class MyClass extends Component {

    constructor() {
        super()
        this.state = {
        data:[]
        }
    }
    MyFunction() {   
       fetch("url").then(res => res.json()).then(data => this.setState({data}))
       .catch(err => console.error(err))
    }

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

答案 2 :(得分:0)

这是使用state的好例子。

myFunction() {
  setInterval(function() {
    let newCount = this.state.count + 1
    this.setState({count: newCount})
  }, 1000)
}
render() {
  return (
    <div>
      Count is {this.state.count}
    </div>
  )
}

您需要在constructor中或在componentDidMount中调用myFunction,并应设置初始状态

constructor(props) {
  super(props)
  this.state = {
    count: 0
  }
  this.myFunction = this.myFunction.bind(this)
}
componentDidMount() {
  this.myFunction()
}

注意:根据您的编译器,您可能需要在函数中添加一些绑定:

setInterval(function() {
  ...
}.bind(this), 1000)

...或者您可以使用粗箭头表示法,该表示法隐式绑定:

setInterval(() => {
  ...
}, 1000)