我正在尝试使用react-native和redux访问侦听器或辅助类中的当前状态 .

我们使用react-native-tcp从tcp套接字获取数据(使用nodejs网络库) . 我试图缩短代码作为更好理解的例子 .

目前的情况:

  • on('data')上的套接字侦听器在componentDidMount中注册 . 如https://reactjs.org/docs/react-component.html#componentdidmount中所述,这应该是一个好点"to load data from a remote endpoint" . 只有我们注册一个监听器,并且不会获取一次数据 .

  • 配置由configurationReducer存储在状态中,configurationReducer将配置加载到componentDidMount上的存储中 . 我们看到这可以通过redux-logger工作 . reducer的初始状态是一个空数组 .

问题:

  • 套接字侦听器中的帮助器方法只能访问配置的初始状态,并且不会更新传递的props .

问题:

  • componentDidMount()是注册套接字侦听器的最佳位置吗?

  • 如何传递配置道具或使当前状态可用于侦听器的回调函数?

  • doSomething(data)帮助器方法中有一些逻辑用于将数据解析为人类可读对象 . 目前,这是由ES6类(辅助类)完成的 . 这是正确的地方还是应该在减速器中进行逻辑?

Update 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);