我有多个用于注册的模式,并且遇到问题。我总共有三个动作。首先是注册按钮,然后激活第一个注册模式,以便用google或facebook注册,然后在完成之后,提供者无法收集的其他信息的模式将显示为提供者收集的预填充输入。我渲染应用程序时渲染两个模态,仅在单击注册按钮时显示它。我需要在完成facebook或google登录后调用componentDidMount,但是当我在app拳头开始时渲染模态时调用它。按钮命中动作减速器和减速器改变类型bool的状态以显示模态或不显示模态。
class HeaderRegisterButton extends Component {
render() {
return(
<div>
<Register1/>
<Register2/>
</div>
);
}
}
注册模式1
class Register1 extends Component {
render() {
return(
<div>
<button onClick={() => this.props.showRegister2()} /> //This would hit the action reducer to get initial info and change the bool to show register 1 to false and register 2 to true.
</div>
);
}
}
注册模式2
import { reduxForm, Field, initialize } from 'redux-form';
class Register2 extends Component {
componentDidMount() {
hInitalize() //only called when the app fires, not when the state changes in the action reducer to change bool to show this modal.
}
hInitalize() {
var initData = {};
const initData = {
"name" = this.props.name//name stored inside redux store
};
this.props.initialize(initData)
}
render() {
return(
<div>
//Code to display the modal which works.
</div>
);
}
}
答案 0 :(得分:16)
componentDidMount
仅在任何组件的生命周期中调用一次,重新渲染不会重新初始化组件。将在您管理逻辑的地方调用componentDidUpdate
。
答案 1 :(得分:9)
componentDidMount 仅在安装React组件时执行一次,并且在状态或道具更改时不执行。
因此,您需要使用 componentDidUpdate ,并且不要忘记比较道具或状态(当在父级组件中更改道具时也可以使用它)
componentDidUpdate(prevProps,prevState) {
if (this.state.userID !== prevState.userID) {
console.log('userId changed ');
}
}
重要:不要在componentDidUpdate中更新状态而不将其包装在某种情况下,因为这会触发重新渲染,并且会导致无限循环
答案 2 :(得分:1)
IMO您不需要调用componentDidMount,只需向父组件提供一些回调,该组件保存过程中所需/收集的所有信息的临时状态。每个模态都将显示此父组件为其提供的信息。
这个过程就是这样的。
希望有道理:)
更新:
我不知道你的实现是怎么样的...但你可以将函数传递给子组件(通过props)并在子组件中使用它们与父组件进行通信,因此在进行Facebook身份验证的组件中父传递someCallback
接受下面显示的参数并将它们添加到父状态(记住状态的改变将导致使用该状态的任何组件更新)。我通过传递fbLoginCallback
作为我的facebook登录过程的回调来完成此操作,该过程调用了Facebook的FB.getLoginStatus(....)
export class FbLoginButton extends Component {
constructor(props) {
super(props);
}
fbLoginCallback = response => {
const { authResponse, status } = response;
if (status === 'connected') {
// Logged into your app and Facebook.
const userId = authResponse.userID;
const accessToken = authResponse.accessToken;
FB.api('/me', user => {
const displayName = user.name;
this.props.someCallback(userId, accessToken, displayName);
});
}
}
}
我删除了实际按钮的渲染以及其他一些小东西,但这或多或少都是回调应该如何。
答案 3 :(得分:0)
componentDidMount是一个生命周期方法,仅在安装组件时才调用。在第一次渲染后仅调用一次。