簡體   English   中英

React Redux將狀態作為道具傳遞給組件

[英]React Redux pass state as props to component

在我的React Redux應用程序中,當主頁面加載時,我想從API獲取數據並顯示它供用戶查看。 正在從操作中獲取數據,並且正在更新狀態。 但是,我沒有將該州視為該組成部分的支柱。 不確定什么沒有正確連接。

家庭組件:

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as actions from '../actions/actions';
import '../styles/homeStyles.css';

class Home extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.props.actions.fetchMovies();
  }

  render() {
    const { movies, isFetching, errorMessage } = this.props;

    if (isFetching && !movies.length) {
      return <p>Loading...</p>;
    }

    //will display movies when I have access to state
    return (
      <div>
        <h1>React Starter App</h1>
        <h2>This is the home page</h2>
      </div> 
    );
  }
}

Home.proptypes = {
  actions: PropTypes.object.isRequired,
  dispatch: PropTypes.func.isRequired,
  movies: PropTypes.array.isRequired,
  isFetching: PropTypes.bool.isRequired,
  errorMessage: PropTypes.string
};

function mapStateToProps(state) {
  return {
    movies: state.movies,
    isFetching: state.isFetching,
    errorMessage: state.errorMessage
  };
}

function mapDispatchToProps(dispatch) {
  return { actions: bindActionCreators(actions, dispatch) };
}

export default connect(mapStateToProps, mapDispatchToProps)(Home);

商店:

import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import { syncHistoryWithStore } from 'react-router-redux';
import { browserHistory } from 'react-router';

import rootReducer from '../reducers/index';

const initialState = {
  movies :{
    movies: [],
    isFetching: false,
    errorMessage: null,
    firstName: null,
    lastName: null,
    email: null
  }
};

const store = createStore(rootReducer, initialState, applyMiddleware(thunkMiddleware, createLogger()));

export const history = syncHistoryWithStore(browserHistory, store);

if (module.hot) {
  module.hot.accept('../reducers/', () => {
    const nextRootReducer = require('../reducers/index').default;
    store.replaceReducer(nextRootReducer);
  });
}

export default store;

應用:

import React, { Component } from 'react';
import Navbar from './Navbar';

class App extends Component {
  render() {
    return (
      <div>
        <Navbar />
        <div className="container">
          {this.props.children}
        </div>
      </div>
    );
  }
}

export default App;

指數:

import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import { Router, Route, IndexRoute } from 'react-router';
import store, { history } from './store/store';
require('./favicon.ico');
import App from './components/App';
import Home from './components/Home';
import Contact from './components/Contact';
import NotFoundPage from './components/NotFoundPage';

const router = (
  <Provider store={store}>
    <Router history={history} >
      <Route path="/" component={App}>
        <IndexRoute component={Home} />
        <Route path="/contact" component={Contact} />
        <Route path="*" component={NotFoundPage} />
      </Route>
    </Router>
  </Provider>
);

render(router, document.getElementById('app'));

減速機:

import * as constants from '../constants/constants';

const initialState = {
  movies: [],
  isFetching: false,
  errorMessage: null
};

const moviesReducer = (state = initialState, action) => {
  switch (action.type) {
    case constants.FETCH_MOVIES : 
      return {
        ...state,
        isFetching: true
      };
    case constants.FETCH_MOVIES_SUCCESS :
      return {
        ...state,
        movies: [action.data],
        isFetching: false
      };
    case constants.FETCH_MOVIES_ERROR :
      return {
        ...state,
        isFetching: false,
        errorMessage: action.message
      };
    default :
      return state;
  }
};

export default moviesReducer;

我在mapStateToProps函數中錯誤地訪問了狀態。 當我在函數中放置一個調試器時,我能夠看到狀態結構,它與我試圖訪問的那個不匹配。

由於我的商店狀態如下所示:

const initialState = {
  movies :{
    movies: [],
    isFetching: false,
    errorMessage: null,
    firstName: null,
    lastName: null,
    email: null
  }
};

我需要在我的組件中更改我的mapStateToProps函數,如下所示:

function mapStateToProps(state) {
  return {
    movies: state.movies.movies,
    isFetching: state.movies.isFetching,
    errorMessage: state.movies.errorMessage
  };
}

這允許正確映射所有內容並訪問組件內的狀態。

從那時起,我在商店中重構我的狀態看起來像這樣:

const initialState = {
  movies: {
    movies: [],
    isFetching: false,
    errorMessage: null
  },
  form: {
    firstName: null,
    lastName: null,
    email: null
  }
};

和我的mapStateToProps函數看起來像:

function mapStateToProps(state) {
  return {
    movies: state.movies
  };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM