反应将状态对象传递给子组件

时间:2020-11-09 09:47:54

标签: reactjs javascript-objects

我对使用React并不陌生,并且遇到了传递状态的问题。

我在App.js中有一个get请求,我正在使用该请求添加要声明的包含对象的对象。然后,我试图将这些数据传递到组件以遍历对象并显示数据。

问题在于组件中没有收集数据,它仅返回货币[对象对象]。如果我将所有内容直接添加到Component中,而不是将状态传递给下层,那么一切都会按预期进行。

在我的组件中,我也不得不注释掉this.createTable(),因为这会导致以下错误:

×
TypeError: Cannot convert undefined or null to object
// Get the keys of the first item.
> 60 | Object.keys(Object.values(data)[0]).forEach(key => {
     | ^  61 |   const header = document.createElement('th');
  62 |   header.textContent = key;
  63 |   headerRow.append(header);

如果有人能指出我正确的方向,那将不胜感激!

应用

class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      error: null,
      isLoaded: false,
      currencies: {}
    };
  }

  componentDidMount() {

    axios.get('https://blockchain.info/ticker') 
      .then((response) => {

        const data = response.data; // Returns an Object containing multiple Objects

        this.setState({
          currencies: data,
          isLoaded: true
        });

      },
      (error) => {
        console.log(error);
      });

  } 

  render() {

    const currencies = this.state.currencies; 
    
    return (
      <div className="app">
        <div className="app__col">
          <CurrencyData currencies={currencies} />
        </div>
        <div className="app__col">
          <p>FORM</p>
        </div>
      </div>
    );
  }
} 
export default App;

组件

class CurrencyData extends Component {


  componentDidMount() {

    const data = this.props.currencies;

    console.log(data);

    // this.createTable(data);


  } // END componentDidMount


  createTable = (data) => {

    const table = document.createElement('table');
    
    // Create headers.
    const headerRow = table.insertRow();
    
    // Empty cell for currency column.
    headerRow.insertCell();
    
    // Get the keys of the first item.
    Object.keys(Object.values(data)[0]).forEach(key => {
      const header = document.createElement('th');
      header.textContent = key;
      headerRow.append(header);
    });

    // Create rows of data.
    Object.entries(data).forEach(([ currency, values ]) => {
      const row = table.insertRow();
      const header = document.createElement('th');
      header.textContent = currency;
      row.append(header);

      Object.values(values).forEach(value => {
        row.insertCell().textContent = value;
      });
    });

    document.querySelector('#table').append(table);
  };

  render() {
    return (
      <div id="table"></div>
    )
  }
}

export default CurrencyData;

2 个答案:

答案 0 :(得分:1)

您有一个空对象作为货币的默认值

因此在这里,如果传递了一个空对象,则会将上述错误作为其未定义内容抛出

Object.keys(Object.values(data)[0]);

因此,您应该先检查一下data!==null and data.length>0

并且您应在将货币设置为空数组时将货币的默认值设置为空数组。

答案 1 :(得分:1)

将此条件添加到您的App.js中,因为在首次呈现货币成分时,它会收到一个空的{}对象,这会导致错误。选中CodeSandBox

{Object.keys(this.state.currencies).length > 0 ? <CurrencyData currencies={this.state.currencies} /> : "loading"}