【问题标题】:Render gets called on state change, props need to be updated on child but the child does not get rerendered在状态更改时调用渲染,需要在子节点上更新道具,但子节点不会重新渲染
【发布时间】:2018-11-05 16:55:41
【问题描述】:

我有以下代码:

// 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');
      }
...

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

【问题讨论】:

  • componentDidMount 只会被调用一次。尝试登录render
  • 可以,谢谢!是否有重新渲染的事件?我想访问我更新的道具,而不会弄乱渲染功能。
  • componentDidUpdate 等。在此处查看所有生命周期 reactjs.org/docs/react-component.html#updating
  • 太棒了,非常感谢.. 我只是在错误的地方搜索

标签: javascript reactjs components rendering web3


【解决方案1】:

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

【讨论】:

  • 这很快就会被弃用,而应该使用getDerivedStateFromProps()
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2020-07-18
  • 2022-06-15
  • 2020-06-26
  • 1970-01-01
  • 2018-11-29
  • 2017-11-16
相关资源
最近更新 更多