设置状态在child后会收到道具吗?
Set state in child after it will receive props?
我有两个组成部分。一个是调用 ajax 请求以获取值的 UserBase。当获取这些值并更新为 header.
状态时
另一个组件是 Header。它是 UserBase 的 child 组件。因此,当状态更新时,它会将其传递给 child 组件。
现在,我的问题是当 child 从 UserBase 组件接收道具时,我必须更新它的状态。我怎样才能实现这个功能。
这是我的代码
Header 组件
var React = require('react');
var Router = require('react-router');
import Auth from './Auth.js';
import PopupSmall from './PopupSmall.js';
var headerStyle = {
border:0
}
class Header extends React.Component{
constructor(){
super();
console.log("constructor");
this.state = {basicInfo : {}};
}
// **some function which needs to tigger when this component will receive props**
popupChange(){
console.log("============popupChange============");
console.log(this.state);
Router.browserHistory.push("/dashboard");
}
render(){
if(this.props.basicInfo){
return (
<div>
{this.props.basicInfo.isAgency==1 ? <PopupSmall popupCallBack={this.popupChange.bind(this)} itemList={this.props.agencies} show='true' title='Agencies'/> : console.log()}
</div>
)
}
}
}
export default Header;
用户基础组件
import React from 'react';
import Header from './Header.js';
import Auth from './Auth.js';
import Loader from './Loader.js';
var Router = require('react-router');
class Base extends React.Component{
constructor(){
super();
this.state = {basicInfo :[]};
}
loadDataFromServer() {
var tokenId = Auth.getCookies("token");
if(tokenId!=""){
var data = {
token : tokenId
}
$.ajax({
url: 'http://xxx.xxxxxxx.xxx/abc/cde',
dataType: 'json',
cache: false,
type : 'POST',
data : JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(response) {
var info = {
compName : response.name,
firstName : response.fn,
isAgency : response.isAgeny
}
this.setState({basicInfo:info}, function(){
//console.log(this.state.data);
}.bind(this));
}.bind(this),
error: function(xhr, status, err) {
console.error("", status, err.toString());
}.bind(this)
});
} else {
Router.browserHistory.push('/login');
}
}
componentDidMount() {
this.loadDataFromServer();
}
render(){
document.body.className="nav-md";
return (
<div className="container body">
<div className="main_container">
<Header basicInfo={this.state.basicInfo} />
</div>
</div>
);
}
}
export default Base;
如果您还没有,请通读一下:https://facebook.github.io/react/docs/component-specs.html
这里有一个功能可以满足您的需求:
componentWillReceiveProps(nextProps, nextState)
Invoked when a component is receiving new props. This method is not called for the initial render.
Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.
所以你的Header组件里面会有类似下面的功能(未测试):
componentWillReceiveProps(nextProps) {
if (nextProps.basicInfo !== this.props.basicInfo) {
this.setState({ basicInfo: nextProps.basicInfo });
}
}
我有两个组成部分。一个是调用 ajax 请求以获取值的 UserBase。当获取这些值并更新为 header.
状态时另一个组件是 Header。它是 UserBase 的 child 组件。因此,当状态更新时,它会将其传递给 child 组件。
现在,我的问题是当 child 从 UserBase 组件接收道具时,我必须更新它的状态。我怎样才能实现这个功能。
这是我的代码
Header 组件
var React = require('react');
var Router = require('react-router');
import Auth from './Auth.js';
import PopupSmall from './PopupSmall.js';
var headerStyle = {
border:0
}
class Header extends React.Component{
constructor(){
super();
console.log("constructor");
this.state = {basicInfo : {}};
}
// **some function which needs to tigger when this component will receive props**
popupChange(){
console.log("============popupChange============");
console.log(this.state);
Router.browserHistory.push("/dashboard");
}
render(){
if(this.props.basicInfo){
return (
<div>
{this.props.basicInfo.isAgency==1 ? <PopupSmall popupCallBack={this.popupChange.bind(this)} itemList={this.props.agencies} show='true' title='Agencies'/> : console.log()}
</div>
)
}
}
}
export default Header;
用户基础组件
import React from 'react';
import Header from './Header.js';
import Auth from './Auth.js';
import Loader from './Loader.js';
var Router = require('react-router');
class Base extends React.Component{
constructor(){
super();
this.state = {basicInfo :[]};
}
loadDataFromServer() {
var tokenId = Auth.getCookies("token");
if(tokenId!=""){
var data = {
token : tokenId
}
$.ajax({
url: 'http://xxx.xxxxxxx.xxx/abc/cde',
dataType: 'json',
cache: false,
type : 'POST',
data : JSON.stringify(data),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
success: function(response) {
var info = {
compName : response.name,
firstName : response.fn,
isAgency : response.isAgeny
}
this.setState({basicInfo:info}, function(){
//console.log(this.state.data);
}.bind(this));
}.bind(this),
error: function(xhr, status, err) {
console.error("", status, err.toString());
}.bind(this)
});
} else {
Router.browserHistory.push('/login');
}
}
componentDidMount() {
this.loadDataFromServer();
}
render(){
document.body.className="nav-md";
return (
<div className="container body">
<div className="main_container">
<Header basicInfo={this.state.basicInfo} />
</div>
</div>
);
}
}
export default Base;
如果您还没有,请通读一下:https://facebook.github.io/react/docs/component-specs.html
这里有一个功能可以满足您的需求:
componentWillReceiveProps(nextProps, nextState)
Invoked when a component is receiving new props. This method is not called for the initial render.
Use this as an opportunity to react to a prop transition before render() is called by updating the state using this.setState(). The old props can be accessed via this.props. Calling this.setState() within this function will not trigger an additional render.
所以你的Header组件里面会有类似下面的功能(未测试):
componentWillReceiveProps(nextProps) {
if (nextProps.basicInfo !== this.props.basicInfo) {
this.setState({ basicInfo: nextProps.basicInfo });
}
}