组件中的 Redux 状态

IT技术 reactjs redux connect
2021-05-03 12:44:55

试图弄清楚如何将 Redux 存储状态从 Redux 提取到我的组件中。我已经连接了 mapStateToProps 和“连接”。但是,当我单击“App”组件中的按钮时,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());
2个回答

看起来你那里有几个问题。

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

let store = createStore(rootReducer)

const ConnectedApp = connect(mapStateToProps)(App);

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

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

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

这应该足以让 App 组件从 Redux 接收数据并分派动作。

这是您应该如何在组件中获取存储状态。

1)创建reducers文件夹并创建一个新文件index.js

/* reducers/index.js */

import { combineReducers } from "redux";
import tweetReducer from "./tweetReducer";

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

export default rootReducer;

/* 减速器/tweetReducer.js */

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

/* 组件/App.js */

import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
    buttonClicked() {
        this.props.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>
         )
     }
}
function mapStateToProps(state) {
   console.log('mapping state to props')
   return {
     tweets: state.tweets
   }
}
export default connect(mapStateToProps)(App);

/* 组件/Display.js */

import React, { Component } from 'react';
  export default class Display extends Component {
     render() {
        return (
            <div>
               <h3>Tweets:</h3>
               {this.props.tweets}
             </div>
        )
     }
  }

/*主.js */

import React, { Component } from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { store } from "./store";

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

/* 存储/index.js */

import { createStore, applyMiddleware, compose } from "redux";
import reducers from "../reducers";

const store = createStore(
    reducers,
    composeEnhancers(applyMiddleware())
);

export { store };