![](/img/trans.png)
[英]How to run a specific javascript code before page load (first of all)?
[英]How to call action in react before the first load of page?
我在componentDidMount
中有一个通过单击调用的操作
onBtnClick = (data: any) => {
this.props.componentDidMount(data);
};
<button onClick={this.onBtnClick}> Toogle posts </button>;
{
this.props.data.map((el: any) => <li key={el.id}>{el.title}</li>);
}
如何在第一页加载之前调用componentDidMount
? 不使用 onClick 函数
componentDidMount
是 React 中的生命周期方法,在组件渲染成功后调用。 您不应该将此属性传递给任何其他组件。
如果您希望在页面完全加载之前调用函数或操作(在调用 componentDidMount 之前),则需要使用UNSAFE_componentWillMount()
,该方法已被弃用,建议您不要使用它。 或者您可以直接在constructor()
方法中调用该操作。 构造函数是第一个被调用的东西。
另一件重要的事情是,你不应该从onClick()
函数调用生命周期方法,它们由 React 本身适当地处理和调用。
如果您需要将组件作为道具传递。 创建一个名为myCustomComponentDidMount()
的函数,而不是componentDidMount()
,然后在应用程序第一次加载之前从constructor()
调用它,然后你也可以将该函数作为 prop 传递给其他人,而不会与componentDidMount()
看看下面的代码结构。 对于 Redux,您需要react-redux
包中提供的connect()
函数。 当调用connect()
函数时,您的 redux 状态会自动映射到组件的道具,因此您不需要再次传递道具,也不需要componentDidMount()
或componentWillMount()
。 只需引用this.props。
我还添加了一些评论供您参考。
// Initial internal state of the component.
state = {}
toggleButton() {
// do something when the button is clicked. }
componentWillMount() {
// DEPRECATED METHOD
// Anything you want to call before the component mounts. }
componentDidMount() {
// Anything you want to call after the component mounts. }
render() {
return (
<div>
<button onClick={this.onBtnClick}>Toggle posts</button>
<ul>
{
// check that the data is available before rendering.
this.props.data && this.props.data.map(el => (
<li key={el.id}>{el.title}</li>
))
}
</ul>
</div>
) } }
// If using Redux, you will need to use mapStateToProps()
const mapStateToProps = state => ({ data: state.data })
connect(mapStateToProps)(/* Your component */ )
希望这有助于React-Redux Doc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.