简体   繁体   English

在 state React 中更新 this.state.data object 时出现问题

[英]issues updating this.state.data object in state React

I have the following App.js file where I try to change 7 state attributes into one easier to manage data object.我有以下 App.js 文件,我尝试将 7 个 state 属性更改为更易于管理数据 object 的属性。 I am following Updating an object with setState in React trying to use the main answer but I have now tried 3 different ways to update state, including the accepted answer, and nothing is working.我正在关注在 React 中使用 setState 更新 object尝试使用主要答案,但我现在尝试了 3 种不同的方法来更新 state,包括接受的答案,但没有任何效果。 I have here App.js:我这里有 App.js:

import React from 'react';

import SearchBar from './SearchBar';
import AllDividendsDisplay from './dividend_results_display/AllDividendsDisplay';
import DividendResultsDisplay from './dividend_results_display/DividendResultsDisplay';

import axios from 'axios';


class App extends React.Component {

  state = {
    loading: false,

    current_price: '',
    recent_dividend_rate: '',
    current_yield: '',
    dividend_change_1_year: '',
    dividend_change_3_year: '',
    dividend_change_5_year: '',
    dividend_change_10_year: '',
    all_dividends: [],
  }

  runStockInfoSearch = async (term) => {
    // clear old data
    this.setState({
      loading: true,

      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    });

    // const host = '67.205.161.47';
    const HOST = 'localhost';
    const base_url = 'http://' + HOST + ':8000'
    const dividends_api_url = base_url + '/dividends/' + term

    axios.get(dividends_api_url, {})
      .then(response => {

        console.log(response.data)

        const RESPONSE_KEYS = [
          'current_price',
          'current_yield',
          'recent_dividend_rate'
        ]
        RESPONSE_KEYS.map((key) => {
          this.setState({[key]: response.data[key]})
        })

        this.setState({all_dividends: response.data['all_dividends'].reverse()})

        const YEARS_CHANGE = [1, 3, 5, 10];
        YEARS_CHANGE.map((year) => {
          const key = 'dividend_change_' + year.toString() + '_year';
          this.setState({[key]: response.data[key]})
        });

        this.setState({loading: false})
      })
      .catch(err => {
        console.log(err);
      })
  }

  render() {

    if (this.state.loading === true) {
      return (
        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <div className="ui segment">
            <div className="ui active dimmer">
              <div className="ui text loader">Loading</div>
            </div>
          </div>
        </div>
      )
    } else {
      return (

        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <DividendResultsDisplay
            current_price={this.state.current_price}
            recent_dividend_rate={this.state.recent_dividend_rate}
            current_yield={this.state.current_yield}
            dividend_change_1_year={this.state.dividend_change_1_year}
            dividend_change_3_year={this.state.dividend_change_3_year}
            dividend_change_5_year={this.state.dividend_change_5_year}
            dividend_change_10_year={this.state.dividend_change_10_year}
            all_dividends={this.state.all_dividends}
          />
        </div>
      )
    }
  }
}



export default App;

The project can be downloaded at https://github.com/codyc4321/dividends_ui该项目可以在https://github.com/codyc4321/dividends_ui下载

I am getting the response data still but cannot update this state to put any data on the screen:我仍然收到响应数据,但无法更新此 state 以将任何数据放在屏幕上:

在此处输入图像描述

Any help appreciated, thank you任何帮助表示赞赏,谢谢

This is the best solution, the simplest way to update a state object:这是最好的解决方案,更新 state object 的最简单方法:

import React from 'react';

import SearchBar from './SearchBar';
import AllDividendsDisplay from './dividend_results_display/AllDividendsDisplay';
import DividendResultsDisplay from './dividend_results_display/DividendResultsDisplay';

import axios from 'axios';


class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      loading: false,

      dividends_data: {
        current_price: '',
        recent_dividend_rate: '',
        current_yield: '',
        dividend_change_1_year: '',
        dividend_change_3_year: '',
        dividend_change_5_year: '',
        dividend_change_10_year: '',
        all_dividends: [],
      }
    }
  }

  updateStateData = (key, value) => {
    const data = this.state.dividends_data;
    data[key] = value;
    this.setState({data});
  }

  runStockInfoSearch = async (term) => {
    console.log("running search")
    // clear old data
    this.setState({
      loading: true,

      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    });

    const HOST = 'localhost';
    const base_url = 'http://' + HOST + ':8000'
    const dividends_api_url = base_url + '/dividends/' + term

    axios.get(dividends_api_url, {})
      .then(response => {

        console.log(response.data)

        const RESPONSE_KEYS = [
          'current_price',
          'current_yield',
          'recent_dividend_rate'
        ]
        RESPONSE_KEYS.map((key) => {
          this.updateStateData(key, response.data[key]);
        })


        this.updateStateData('all_dividends', response.data['all_dividends'].reverse());


        const YEARS_CHANGE = [1, 3, 5, 10];
        YEARS_CHANGE.map((year) => {
          const key = 'dividend_change_' + year.toString() + '_year';
          this.updateStateData(key, response.data[key]);
        });

        this.setState({loading: false})
      })
      .catch(err => {
        console.log(err);
      })
  }

  render() {

    if (this.state.loading === true) {
      return (
        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <div className="ui segment">
            <div className="ui active dimmer">
              <div className="ui text loader">Loading</div>
            </div>
          </div>
        </div>
      )
    } else {
      return (

        <div className="ui container" style={{marginTop: '10px'}}>
          <SearchBar runSearch={this.runStockInfoSearch} />
          <DividendResultsDisplay
            data={this.state.dividends_data}
          />
        </div>
      )
    }
  }
}



export default App;

You need to call the constructor function to add a state.您需要调用构造函数 function 来添加 state。 For that, change this piece of code:为此,更改这段代码:

  state = {
    loading: false,

    dividends_data: {
      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    }
  }

with this one:有了这个:

 constructor(props) {
    super(props);
    this.state = {
    loading: false,
    dividends_data: {
      current_price: '',
      recent_dividend_rate: '',
      current_yield: '',
      dividend_change_1_year: '',
      dividend_change_3_year: '',
      dividend_change_5_year: '',
      dividend_change_10_year: '',
      all_dividends: [],
    }
  };
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM