连接动作创建者时,数据不会出现在组件中,减少者使用redux-thunk

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (8)

我在将所有部分组合在一起时遇到问题,以便能够在我的组件上显示数据。我可以在chrome控制台上看到数据显示,并且我没有在页面上出现任何错误,但数据没有出现在我的组件上。

如果有人能帮我看看我做错了什么和/或我能做得更好

下面是代码片段。

actionCreator

// @flow
// [TODO]: Add flow

import axios from 'axios';

const ROOT_URL = `https://toilets.freska.io/toilets`;

// const Actions = /* [TODO]: add flow */

export const FETCH_TOILETS = 'FETCH_TOILETS';
export const FETCH_TOILETS_PENDING = 'FETCH_TOILETS_PENDING';
export const FETCH_TOILETS_ERROR = 'FETCH_TOILETS_ERROR';

export function fetchToilets() {
    const url = `${ROOT_URL}`;  
    const request = axios.get(url);

    return dispatch => {
    console.log(`IN ACTION fetchToilets`);

    dispatch({ type: FETCH_TOILETS_PENDING })
    axios.get(url)
    .then(
      response => dispatch({
        type: FETCH_TOILETS,
        payload: response
    }),
      error => dispatch({ type: FETCH_TOILETS_ERROR, payload: error })
    );
    };
};

reducer_cardListrootReducer

// @flow
// [TODO]: Add flow

import { FETCH_TOILETS } from '../actions';

// type State = {} /* [TODO]: add @flow */

const initialState = [];

const CardListReducer = (state: State = initialState, action:Action ): State => {
    switch(action.type) {
        case FETCH_TOILETS:
            return [  ...state, action.payload.data ];
        default:
            state;
    }
    return state;
}

export default CardListReducer;


// rootReducer

// @flow
// [TODO]: Add flow
import { combineReducers } from 'redux';
import CardListReducer from './reducer_cardList';

const rootReducer = combineReducers({
  toilets: CardListReducer
});

export default rootReducer;

index.js

// @flow
// [TODO]: add @flow

import * as React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { createStore, applyMiddleware, compose } from 'redux';

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

import './index.css';

import registerServiceWorker from './registerServiceWorker';

const rootElement = document.getElementById('root');

const configueStore = createStore(
    rootReducer,
    applyMiddleware(thunk)
);

ReactDOM.render(
  <Provider store={configueStore}>
    <App />
  </Provider>
  ,
  rootElement
);

registerServiceWorker();

CardList.js

/* @flow */
// [TODO]: add flow

import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchToilets } from '../../actions';


import CardItem from '../../components/CardItem/CardItem';
import './CardList.css';


type CardListProps = {
  cards?: React.Node<any>
}

class CardList extends React.Component<CardListProps,{}> {

  renderToilet() {
    const toilets = this.props.toilets;
    //const toilet = toilets.map(e => e.id)

    console.log(`These are all the toilets: ${JSON.stringify(toilets)}`); // [[{"id":1,"map_id":"TOILET1","queue_time":1800,"queue_level":1,"type":"male","location":""}, ...etc
    //console.log(`This is the toilet info: ${JSON.stringify(toilet)}`);

    const id = toilets.map(toilet => toilet.id);
    const mapId = toilets.map(toilet => toilet.map_id);

    console.log(`This is the id: ${JSON.stringify(id)} and the mapId: ${JSON.stringify(mapId)}`); // This is the id: [null] and the mapId: [null]

    // const queueTime = data.map(toilet => toilet.queue_time);
    // const queueLevel = data.map(toilet => toilet.queue_level);
    // const type = data.map(toilet => toilet.type);
    // const location = data.map(toilet => toilet.location);

    return (
      <li key={id}> 
       <p>{mapId}</p>
       {/*<p>{queueTime}</p>
       <p>{queueLevel}</p>
       <p>{type}</p>
       <p>{location}</p> */}
      </li>
    )
  }

  componentDidMount() {
    console.log(`fetchToilets() actionCreator: ${this.props.fetchToilets()}`);
    this.props.fetchToilets();
  }


  render() {
        return(
      <section>      
            <ul className='card-list'>
          {/* { this.props.toilet.map(this.renderToilet) } */}
          { this.renderToilet() } 
            </ul>
      </section>
        )
    }
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators({ fetchToilets }, dispatch);
}

const mapStateToProps = ({ toilets }) => {
  return { toilets }
};

export default connect(mapStateToProps, mapDispatchToProps)(CardList);
提问于
用户回答回答于

你需要更新你的减速机

const CardListReducer = (state: State = initialState, action:Action ): State => {
    switch(action.type) {
        case FETCH_TOILETS:
            return [  ...state, ...action.payload.data ];
        default:
            state;
    }
    return state;
}

你的旧线

return [  ...state, action.payload.data ]

用。。。来代替

 return [  ...state, ...action.payload.data ];

如果你想每次加载那么你可以简单

    return  action.payload.data;

和你的渲染功能

renderToilet() {
    const toilets = this.props.toilets;   

  return arr.map((item, id) =><li key={id}> 
       <p>{item.id}</p>
       {/*<p>{queueTime}</p>
       <p>{queueLevel}</p>
       <p>{type}</p>
       <p>{location}</p> */}
      </li>)


  }

扫码关注云+社区

领取腾讯云代金券