【问题标题】:How to pass a state variable into a function in React?如何将状态变量传递给 React 中的函数?
【发布时间】:2021-01-06 16:05:43
【问题描述】:

众所周知,可以在 react js 文件中声明状态变量,并让这些状态变量出现在 render() 函数中。

但是,我遇到了一个应用程序,在该应用程序中,我必须获取某些状态变量的值并将它们的值传递给一个名为“数据”的对象(参见下面的代码),该对象会馈送到制作表格的组件中(如 bar图表、图表等)。我正在尝试使用来自 HTTP 的 GET 请求来获取状态变量的值,这可以正常工作(我希望),但状态变量根本不会进入数据数组data: []。我会很感激一些帮助。更多代码如下。


  constructor(props) {
    super(props);
    this.state = {
      teacher_name: '',
      confusion: 0,
      surprised: 0,
      happy: 0,
      sad: 0,
}

componentDidMount() {
    axios.get('http://localhost:8000/api/school/frames/' + localStorage.getItem('first_name') + '_' + localStorage.getItem('last_name'))
    .then(response =>
    {
      
      this.setState({teacher_name: response.teacher_name, confusion: response.confusion, surprised: response.surprised, happy: 100, sad: response.sad})
      console.log(response)
    })
    .catch(error => {
      console.log(error)
    })
  }

  data = {
    labels: ["Happy", "Sad", "Surprised", "Confused"],
    datasets: [this.state.happy(), {
      label: '# of Votes',
      data: [**ATTEMPTING TO PUT STATE VARIABLES HERE**],
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(255, 206, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(255, 159, 64, 0.2)'
      ],
      borderColor: [
        'rgba(255,99,132,1)',
        'rgba(54, 162, 235, 1)',
        'rgba(255, 206, 86, 1)',
        'rgba(75, 192, 192, 1)',
        'rgba(153, 102, 255, 1)',
        'rgba(255, 159, 64, 1)'
      ],
      borderWidth: 1,
      fill: false
    }]
};

【问题讨论】:

  • 您要在数据数组中存储哪些状态值?还有什么理由不使用数据对象作为状态值?如果您在状态中定义数据对象,您可以稍后将此状态对象作为道具传递给需要此信息的组件

标签: javascript reactjs axios state


【解决方案1】:
data =[{this.state.yourState}]

var myData = this.state.yourState

data = {
    labels: ["Happy", "Sad", "Surprised", "Confused"],
    datasets: [this.state.happy(), {
      label: '# of Votes',
      data: [{myData}],

...
}

var myData = this.state.yourState

data = {
    labels: ["Happy", "Sad", "Surprised", "Confused"],
    datasets: [this.state.happy(), {
      label: '# of Votes',
      data: [myData],

...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多