在组件渲染之前获取信息但不能使用 getInitialProps ReactJS
Getting information before Component is rendered but cannot use getInitialProps ReactJS
我在下面有一些代码。我需要在 metamask 注入 web3 之后但在它呈现之前通过调用获取信息,但我不能使用 getInitialProps 因为它会因为服务器端呈现而失败。不太确定如何设计。
class CampaignIndex extends Component {
async componentDidMount() {
const accounts = await web3.eth.getAccounts();
const campaigns = await factory.methods
.getCampaigns("0x0000000000000000000000000000000000000000", 0)
.call({
from: accounts[0]
});
console.log(campaigns["completedCampaigns"]);
console.log(campaigns["ongoingCampaigns"]);
return { campaigns };
}
render() {
return <div>{this.props.campaigns["completedCampaigns"][0]}</div>
}
}
export default CampaignIndex;
错误:TypeError:无法读取未定义的 属性 'completedCampaigns'
我认为使用 setState
更好。您使用 props
的方式不正确。
async componentDidMount() {
const accounts = await web3.eth.getAccounts();
const campaigns = await factory.methods
.getCampaigns("0x0000000000000000000000000000000000000000", 0)
.call({
from: accounts[0]
});
console.log(campaigns["completedCampaigns"]);
console.log(campaigns["ongoingCampaigns"]);
this.setState({
campaigns:campaigns
})
}
render() {
return <div>{this.state.campaigns["completedCampaigns"][0]}</div>
}
我在下面有一些代码。我需要在 metamask 注入 web3 之后但在它呈现之前通过调用获取信息,但我不能使用 getInitialProps 因为它会因为服务器端呈现而失败。不太确定如何设计。
class CampaignIndex extends Component {
async componentDidMount() {
const accounts = await web3.eth.getAccounts();
const campaigns = await factory.methods
.getCampaigns("0x0000000000000000000000000000000000000000", 0)
.call({
from: accounts[0]
});
console.log(campaigns["completedCampaigns"]);
console.log(campaigns["ongoingCampaigns"]);
return { campaigns };
}
render() {
return <div>{this.props.campaigns["completedCampaigns"][0]}</div>
}
}
export default CampaignIndex;
错误:TypeError:无法读取未定义的 属性 'completedCampaigns'
我认为使用 setState
更好。您使用 props
的方式不正确。
async componentDidMount() {
const accounts = await web3.eth.getAccounts();
const campaigns = await factory.methods
.getCampaigns("0x0000000000000000000000000000000000000000", 0)
.call({
from: accounts[0]
});
console.log(campaigns["completedCampaigns"]);
console.log(campaigns["ongoingCampaigns"]);
this.setState({
campaigns:campaigns
})
}
render() {
return <div>{this.state.campaigns["completedCampaigns"][0]}</div>
}