我正在尝试使用react-native和redux访问侦听器或帮助器类中的当前状态。
我们正在使用react-native-tcp从tcp套接字获取数据(使用nodejs网络库)。我试图以缩短代码为例,以便更好地理解。
当前情况:
问题:
问题:
更新1: 我通过为我的套接字连接实现中间件来解决它,如此处推荐的:https://redux.js.org/faq/codestructure#where-should-websockets-and-other-persistent-connections-live和本示例:https://gist.github.com/markerikson/3df1cf5abbac57820a20059287b4be58
然后,我使用“ store.getState()。configuration”传递状态下的配置。如果仍然有人对我的问题有建议,我将很高兴听到他们的建议。
class MyApp extends Component {
componentDidMount() {
// ... create socket, connect to server
// add configuration to state by reducer = [ configuration: [ 'config1': 1, 'config2': 2 ] ]
// register listener to handle data, https://nodejs.org/api/net.html
socket.on('data', (data) => {
doSomething(data);
});
const { configuration } = this.props; // I think here is the problem, because componentDidMount does only have access to the initial state.
function doSomething(data) {
console.log(configuration);
// first problem: configuration is always initial state = [] and will not be updated.
}
}
}
const mapStateToProps = state => {
return {
configuration: state.configuration,
};
};
export default connect(mapStateToProps)(MyApp);