2017-09-24 54 views
0

我正在寻找这么多的方式来解决这个内部状态,但没有一个人的作品,setState仍然不是这里的componentWillReciveProps方法里面工作是我的代码:反应母语:未更新componentWillReciveProps

export class Detail extends React.Component 
{ 
    constructor(props) 
    { 
    super(props); 
    this.state = { 
     ids: 'ger' 
    } 
    } 

    componentWillReceiveProps(nextProps) { 
    this.setState({ ids: nextProps.data },() => { 
      console.log(nextProps.data+"=this id") 
     }); 
    } 


    render() 
    { 
    return (
     <View> 
     <Text>{this.state.ids}</Text> 
     </View> 
    ); 
    } 
} 

如果我做console.log(nextProps.data+"=this id")它可以将我想更新的ID返回到this.state.ids。但在<Text>{this.state.ids}</Text>中,渲染仍显示默认值this.state.ids('ger'),表示this.state.ids未在componentWillReceiveProps中更新。

+0

我认为这与你的[上一个问题](https://stackoverflow.com/q/46389012/2315280)有关,并且可能是由于你的渲染项目上没有'key' prop 'ListView'。请看看[这个答案](https://stackoverflow.com/a/35229429/2315280) – bennygenel

+0

我试过这种方式,仍然得到这个问题,奇怪的是'nextProps.data'获得id时成功我做'console.log(nextProps.data +“=这个id”)'(例如,输出是“4 = this id”),但ids状态仍然没有更新,即使我已经做了'this.setState({ids :nextProps.data})''componentWillReceiveProps''内:'( – janotama

回答

1

setState()并不总是立即更新组件。

你可以在here找到所有你需要的。

实际上作为react文档saya“React在安装时不会调用componentWillReceiveProps和初始道具,只有在某些组件的道具可能更新时才调用此方法,调用this.setState通常不会触发componentWillReceiveProps。

你可以找到更多here

0

这看起来像一个反模式给我。为什么不直接将nextProps.data作为ID注入到Detail组件中?然后你就可以输出的ID直接像这样:

<Text>{this.props.ids}</Text> 

通常你也应该得到一个警告,在“componentWillReceiveProps”调用的setState不会有任何效果。如果你真的想更新你的状态,你可以做“this.state.ids = nextProps.data”我想。

+0

我相信你对设置状态是错误的。请检查[正确使用状态的反应文档](https://facebook.github.io/react/docs/ state-and-lifecycle.html#using-state-correctly)获得更多关于它的信息 – bennygenel

+0

我知道,使用this.state.something =设置状态会设置状态,但不会重新渲染组件,但是在componentWillReceiveProps之后,该组件应该重新渲染,因为道具改变了,除非shouldComponentUpdate返回false。但正如我所说的设置stat这种方式并不是很好的做法。 – justadudewhohacks