2016-12-25 138 views
2

我正在处理React Native项目,并且我意识到React Native似乎打破了React流(Parent to children)道具更新。React Native不更新子组件道具

基本上,我从一个“App”组件调用一个“Menu”组件,将一个道具传递给“Menu”。但是,当我更新“应用程序”状态时,“菜单”上的道具应该更新,但这不会发生。难道我做错了什么?

这是我的代码:

App.js

import React from 'react'; 
import { 
View, 
Text 
} from 'react-native'; 

import Menu from './Menu'; 

class App extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     opacity: 2 
    } 
    } 

    componentDidMount() { 
    setTimeout(() => { 
     this.setState({ 
     opacity: 4 
     }); 
    }, 3000); 
    } 

    render() { 
    return(
     <View> 
     <Menu propOpacity={this.state.opacity} /> 
     </View> 
    ); 
    } 
} 

export default App; 

Menu.js

import React from 'react'; 
import { 
View, 
Text 
} from 'react-native'; 

class Menu extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     menuOpacity: props.propOpacity 
    } 
    } 

    render() { 
    return(
     <View> 
     <Text>Menu opacity: {this.state.menuOpacity}</Text> 
     </View> 
    ); 
    } 
} 

Menu.propTypes = { 
    propOpacity: React.PropTypes.number 
} 

Menu.defaultProps = { 
    propOpacity: 1 
} 

export default Menu; 
+0

不能设置状态里面didmount,让皮斯更新别处。 – Codesingh

+0

@Codesingh yes你可以从'cDM'方法设置状态。你不能从'render'方法这样做。 – Andreyco

回答

1

REACT为没有违反数据流...你。在初始状态初始化之后,当父母发送更新的道具时,您忘记稍后更新菜单的状态。

尝试......

class Menu extends React.Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     menuOpacity: props.propOpacity 
    } 
    } 

    componentWillUpdate(nextProps, nextState) { 
     nextState.menuOpacity = nextProps.propOpacity; 
    } 

    render() { 
    return(
     <View> 
     <Text>Menu opacity: {this.state.menuOpacity}</Text> 
     </View> 
    ); 
    } 
} 
+0

你不能在willupdate里更新状态像这样 – Codesingh

+0

请问你为什么这么认为?这是合法的方式,不会破坏一件事物并为您节省另一次重新渲染。仔细看看构造函数 - 状态从父类传递的道具初始化。我在'componentWillUpdate'方法中使用了非常相同的模式。组件*即将更新*(您无法防止发生这种情况),并且状态将被修改的'nextState'替换。 – Andreyco

+0

嗨@Andreyco,你的解决方案可行。起初,感谢您的帮助。所以,我有一个问题,为什么我需要componentWillUpdate而不是纯React应用程序?我用纯React做了一个例子,并且没有componentWillUpdate,所有工作都正常。 –

相关问题