您好我有兩個反應成分parent
和child
兩者都被連接到redux
store
以相同的對象和對象從服務器asynchronously
componentWillReceiveProps()未在子組件中執行?
問題得到數據:在收到新道具父母的componentWillReceiveProps
得到執行,但孩子的componentWillReceiveProps
未執行 任何想法?
子組件
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
class Child extends Component{
constructor(props) {
super(props);
this.handleUserClick = this.handleUserClick.bind(this)
}
handleUserClick(event){
event.preventDefault();
let userInfo = {
email: '[email protected]',
password: 'password',
};
this.props.someAction(userInfo); // changes the store but on store change componentWillReceiveProps not executing
}
componentWillReceiveProps(nextProps){
console.log(nextProps)
}
render(){
return (
<div><form onSubmit={this.handleUserClick}></form></div>
)
}
}
function matchDispatchToProps(dispatch) {
return bindActionCreators(
{ someAction: someAction}, dispatch)
}
function mapStateToProps (state){
return {
dummyState: state.dummyState
};
}
export default connect(mapStateToProps, matchDispatchToProps)(Child);
當我點擊handleUserClick
是得到執行,但對從服務器child
componentWillReceiveProps
接收數據不被執行,但parent
componentWillReceiveProps
正在執行
我父組件
import React from 'react';
import { connect } from 'react-redux';
import {bindActionCreators} from 'redux';
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {parentState: 0}
}
componentDidMount() {
this.props.someAction(); // same action called in child component
}
componentWillReceiveProps(nextProps){
// it gets executed and call child render function
if(nextProps.something === true){
this.setState({parentState: 1 })
}
if(nextProps.something === false){
this.setState({parentState: -1})
}
}
render() {
if(this.state.parentState == -1){
return(
<Child/>
)
}
else{
return(null)
}
}
}
function matchDispatchToProps(dispatch) {
return bindActionCreators(
{ someAction: someAction}, dispatch) //same action in child component called
}
function mapStateToProps (state){
return {
dummyState: state.dummyState // //same state in child component called
};
}
export default connect(mapStateToProps, matchDispatchToProps)(Parent);
已添加最新代碼 – ashwintastic
嘗試在子中使用'componentWillMount'。 –
我需要使用setState並使用'componentWillMount'不會調用渲染 – ashwintastic