reactjs - 组件中的 Redux 状态

标签 reactjs redux

我正在尝试弄清楚如何将 Redux 存储状态从 Redux 拉入我的组件中。我已经连接了 mapStateToPropsconnect。但是,当我单击 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());

最佳答案

看起来您遇到了一些问题。

首先,了解 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 。因此,您的应用程序组件应该如下所示:

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

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

关于reactjs - 组件中的 Redux 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43900836/

相关文章:

javascript - 在使用我的 action creators 时,有没有办法从全局 Vanilla JS 函数与我的 Redux 存储进行通信?

reactjs - 测试 React 事件处理程序

Reactjs componentWillUnmount 没有被调用

reactjs - Material-UI Accordion(以前称为 ExpansionTable)组件不会导入

reactjs - 在异步 componentDidMount 时使用 React 的 Jest 和 Enzyme 进行测试

reactjs - 如何处理redux表单提交的数据

reactjs - React 和 Redux 工具包 - promise 后拒绝

reactjs - 如何使用 redux-form 选择器使syncErrors脱离状态

javascript - 如何从数组中的对象获取帖子类别

javascript - 通过不等式查询firestore