我对React很陌生,我遇到了在容器中更新道具的问题。我正在使用WebSockets更新我的状态,并且我的mapStateToProps函数中正在更新道具,但我的componentWillReceiveProps不会被调用。
当套接字发出时,updateGameVariables
调用一个Action发送发送的数据,然后发送到我的reducer,它使用Spread Operator来更新状态。然后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 :(得分:0)
您的reducer代码中可能存在突变问题,并且由于React将游戏数组视为相同,因此决定不更新渲染。它解释了为什么
rand: Math.random()
help React意识到props对象中有更新并触发重新渲染。
http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html可能有所帮助。