2017-08-25 57 views
1

我想在我的反应原生应用程序中使用REDX ,我使我的reducer正确(我认为),然后创建商店,然后使用调度或存储,但我得到错误实际上我不能使用派遣无法访问存储在REDX应用程序

我app.js:

const store = createStore(rootReducer, applyMiddleware(logger)); 
export default class taav extends Component { 
render() { 
    return (
     <Provider store={store}> 
      <Chatroom /> 
     </Provider> 
    ); 
} 
} 

和我的聊天室:

import React, {Component} from 'react'; 
import {Text, Button, TabBarIOS, View} from 'react-native' 
import MessageList from './messageList' 
import {connect} from 'react-redux' 


const mapStateToProps = (state) => { 
return { 
    testtest: state.chatroom.teststore.test 
} 
} 

    export const Testredux = connect(mapStateToProps)(MessageList) 


     export default class Chatroom extends Component { 
    state = { 
    test2: "dfsd" 
} 

componentDidMount() { 
    console.log('this') 
} 

btn() { 


    dispatch({type: 'test1'})////////////this is wrong??? 
} 

render() { 

    return (
     <View> 
      <Testredux test={'sdfdsf'}/> 
      <Button title={'sdfsdf'} onPress={this.btn.bind(this)}/> 
     </View> ) 


} 


} 

你知道为什么我不能使用派遣????

回答

0

你连接错误的类

export const Testredux = connect(mapStateToProps)(MessageList) 

应该

export const Testredux = connect(mapStateToProps)(Chatroom) 
+0

不,我要连接的是事情将MessageList @hairmot –

+0

,因为它是你,,聊天室组件没有连接到商店。通过将组件传递给connect函数来连接组件。如果您未连接到商店,则无法分派操作。 – hairmot

+0

这意味着我可以从我已经连接的组件发送?也许我想从一个组件,但我从来没有连接,但实际上,我认为我可以访问存储和发送任何我想要的因为我发送提供商的商店。@ hairmot –

1

您还没有导入“调度”功能,任何地方,所以这就是为什么你不能使用它。你将不得不导入你的商店,然后调用store.dispatch()。

然而,最好的(推荐)的方法是使用mapDispatchToProps从反应 - 终极版连接功能,当您导出聊天室组件:

function mapDispatchToProps(dispatch) { 
    return({ 
     sendTestAction:() => { dispatch({type: 'test1'}) } 
    }) 
} 

...和然后用它来与连接这样当您导出组件:

connect(mapStateToProps, mapDispatchToProps)(Chatroom) 

在你聊天室组件,您可以再做:

render() { 
    return (
     <View> 
      <Testredux test={ 'sdfdsf' }/> 
      <Button title={ 'sdfsdf' } onPress={ this.props.sendTestAction }/> 
     </View> 
    ) 
} 

我希望这有助于。

0

dispatch是传递给包装在connect调用中的组件的道具。由于你包装MessageList而不是Chatroom,因此Chatroom的实例无法访问Redux传递的任何道具。

此外,dispatch应该为道具进行访问,所以它应该是this.props.dispatch,而不是仅仅dispatch

btn() { 
    this.props.dispatch({type: 'test1'}) 
}