首页 > 解决方案 > 在状态更改时调用渲染,需要在子节点上更新道具,但子节点不会重新渲染

问题描述

我有以下代码:

// Packages
import React, { Component } from 'react';
import Web3 from 'web3';
import Header from './components/Header';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      account: null,
      contract: null,
    }

  }

  componentDidMount = () => {
    if (typeof window.web3 !== 'undefined') {
        this.state.web3.eth.getAccounts((err, accounts) => {
          if(err)
              throw err;
          } else {
            this.state.web3.eth.defaultAccount = accounts[0];
            this.contract = new this.state.web3.eth.Contract(abi.abi, this.contractAddress);
            this.setState({
              account : accounts[0],
              contract : this.contract
            });

          }
      });
    } else {
        console.log('No web3? You should consider trying MetaMask!')
    }
  }

  render() {
    console.log(this.state);
    return (

      <div className="App">
        <Header
          account = {this.state.account}
          web3={this.state.web3}
          contract={this.state.contract}
        />          </div>
    );
  }
}

export default App;

如果 setState 已完成,我希望 Header 组件重新渲染,并且在 componentDidMount 中的 setState 函数之后使用更新的状态调用渲染函数。

如果我登录我的 Header 组件,它只会被调用一次并且道具不会得到更新..

...
    class Header extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          accountBalance: "-",
          formattedAddress: '0x0...000',
          account: '0x0'
        }

      }

      componentDidMount(){
        console.log('rendered');
      }
...

我完全不知道可能出了什么问题..

标签: javascriptreactjscomponentsrenderingweb3

解决方案


在您的情况下, componentWillReceiveProps() 是处理更新的道具值的合适生命周期方法。你可以在这里阅读: https ://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1


推荐阅读