javascript - 在状态更改时调用渲染,需要在子节点上更新道具,但子节点不会重新渲染
问题描述
我有以下代码:
// 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');
}
...
我完全不知道可能出了什么问题..
解决方案
在您的情况下, componentWillReceiveProps() 是处理更新的道具值的合适生命周期方法。你可以在这里阅读: https ://engineering.musefind.com/react-lifecycle-methods-how-and-when-to-use-them-2111a1b692b1
推荐阅读
- reactjs - ExpectSaga put 断言因多个 put 效果而失败
- java - Springboot findBy 列表
休眠@Query - android - 使用导航时如何不刷新列表?
- html - 使用 XPATH 在 div 中查找 div 中的文本
- apache-kafka-streams - 从转换中的数据更新全局存储
- c# - 使用 Vision 框架 NSInvalidArgumentException 的 xamarin iOS 人脸检测
- r - 转置一个df,每行作为R中的一列
- javascript - 根据子字符串选择 ID
- c++ - `cin.clear()` 使输入流处于失败状态
- git - 如何在 git 日志中查询 Co-Authored-By