2017-08-15 68 views
0

我對React非常陌生,我遇到了更新容器中道具的問題。我正在使用WebSockets更新我的狀態,並且在我的mapStateToProps函數中正在更新道具,但我的componentWillReceiveProps不會被調用,儘管如此。反應本機道具不更新

當插座發出時,updateGameVariables調用發送發出的數據的動作,然後發送到使用擴展運算符更新狀態的減速器。然後mapStateToProps記錄正確的數據(正在更新)。

這是我處理的主文件(一切都被正確導入我只是想削減代碼):

class GameList extends Component { 
    constructor(props){ 
     super(props); 
     this.ds = new ListView.DataSource({ rowHasChanged: (r1,r2) => r1 !== r2}) 
     const { games } = props; 
     this.state = { 
      games: this.ds.cloneWithRows(games) 
     } 
     this.socket = SocketIOClient('http://localhost:9615',{ transports: ['websocket'], query: 'r_var=17' }); 
     this.socket.on('appGames', function(results){ 
      props.dispatch(updateGameVariables(results)) 
     }); 
    } 

    componentWillReceiveProps(nextProps){ 
     this.setState({ 
      games: this.ds.cloneWithRows(nextProps.games) 
     }) 
    } 

    render() { 
     let { games } = this.state; 
     return (
      <View style={styles.list}> 
       <ListView 
        dataSource={games} 
        renderRow={(rowData, sectionID, rowID) => 
         <TouchableOpacity> 
          <GameIntro key={rowID} game={rowData} /> 
         </TouchableOpacity> 
        } 
       > 
       </ListView> 
     </View> 
     ) 
    } 
} 

function mapStateToProps({games}){ 
    return { 
     games: games.games, // Array 
     // rand: Math.random() 
    } 
} 

function mapDispatchToProps(dispatch) { 
    let actions = bindActionCreators({ updateGameVariables }); 
    return { ...actions, dispatch }; 
} 

export default connect(mapStateToProps, mapDispatchToProps)(GameList) 

這裏是正在被引用的GameIntro組件。

export default props => { 
    let { game } = props; 
    return (
     <View style={styles.itemContainer}> 
      <View style={styles.game_timerow}> 
       <Text style={styles.game_time}>{game.period} {game.minutes}:{game.seconds}</Text> 
      </View> 
     </View> 
    ) 
} 

此外作爲一個說明,當我有rand: Math.random()函數取消註釋所有更新都正常。所以我覺得反應根本就不在更新遊戲陣列。或者我只是不瞭解React的核心概念。任何幫助將不勝感激!

+0

你是否在'componentWillReceiveProps'內部登錄了任何東西以確保它不被調用? – nbkhope

+0

@nbkhope是的,我真的沒有被調用,除非我在那裏有'rand'行。 – RandyMarsh

+0

那麼,你是否在render()中控制日誌記錄?如果有新的道具或狀態,渲染功能將被再次調用。你必須知道你的道具/狀態是否真的在變化。 – nbkhope

回答