组件中的Redux状态

Ton*_*ins 5 connect reactjs redux

试图弄清楚如何将Redux存储状态从Redux拉到我的组件中。我已经将mapStateToProps和“连接”连接起来。但是,当我单击“应用”组件中的按钮时,this.props中没有Redux值。

// React and Redux Const
const { Component } = React;
const { render } = ReactDOM;
const { Provider, connect } = ReactRedux;
const {createStore, combineReducers, bindActionCreators } = Redux;



function tweetReducer(state=[],action) {
    if(action.type === 'ADD_TWEET') {
        return state.concat({ id: Date.now(), tweet: action.payload})
    } else {
        return state;
    }
}

const rootReducer = combineReducers ({
    state: (state = {}) => state,
    tweets: tweetReducer
});


class App extends Component{
    buttonClicked() {
        store.dispatch({type: 'ADD_TWEET', payload: 'This is my first 
tweet!'});
        console.log(this.props)
    }
    render() {
        return (
            <div>
                <h5>Hello from App</h5>
                <button onClick={this.buttonClicked.bind(this)}>Button</button>

                <div>-------------------</div>
                <Display />
            </div>
         )
     }
}

class Display extends Component {
    render() {
        return (
            <div>
                <h3>Tweets:</h3>
                {this.props.tweets}
            </div>
        )
    }
}

function mapStateToProps(state) {
    console.log('mapping state to props')

    return {
        tweets: state.tweets
    }
}

let store = createStore(rootReducer)

render (
    <Provider store={store}>
        <App />
    </Provider>
    , document.querySelector('#app')
);
connect(mapStateToProps)(App)

console.log(store.getState());
Run Code Online (Sandbox Code Playgroud)

mar*_*son 3

看来你有几个问题。

首先,它有助于理解connect()(MyComponent)返回一个“包裹”“真实”组件的新组件。在您的示例中,您在渲染connect() 调用<App />并且实际上并未保存和使用 生成的组件connect()。你需要的是这样的:

let store = createStore(rootReducer)

const ConnectedApp = connect(mapStateToProps)(App);

render(
    <Provider store={store}>
        <ConnectedApp />
    </Provider>
, document.querySelector('#app')
);
Run Code Online (Sandbox Code Playgroud)

其次,连接组件的部分要点是它实际上不应该直接引用存储。 connect()可以采用第二个参数,称为mapDispatchToProps。如果您不提供mapDispatch参数,它会自动提供您的组件this.props.dispatch。因此,您的应用程序组件应该如下所示:

class App extends Component{
    buttonClicked(){
        this.props.dispatch({type: 'ADD_TWEET', payload: 'This is my first tweet!'});
        console.log(this.props)
    }
Run Code Online (Sandbox Code Playgroud)

这应该足以让 App 组件从 Redux 接收数据并调度操作。