2016-12-25 137 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,所有工作都正常。 –

相關問題