繁体   English   中英

状态未使用react redux thunk更新

[英]State not updating with react redux thunk

我对使用redux和反应有点陌生。 我正在尝试使用redux进行简单的API调用,并使其在React中呈现。 我可以看到API调用在redux开发工具的有效负载中正常工作,但是我似乎无法在`connect?中获得它来更新状态。

actions/index

import FilmAPI from '../api/api';

export const FETCH_FILMS = 'FETCH_FILMS';
export const RECEIVE_FILMS = 'RECEIVE_FILMS';

export const receiveFilms = (films) => {
  return {
    type: RECEIVE_FILMS,
    films
  };
}

    export const fetchFilmsRequest = () => {
  return dispatch => {
    return axios.get('https://www.snagfilms.com/apis/films.json?limit=10')
      .then(response => {
        dispatch(receiveFilms(response.data))
      })
  }
}

export default fetchFilmsRequest;

reducers/FilmReducer

import RECEIVE_FILMS from '../actions/index';

export function films (state = [], action) {
 switch (action.type) {
    case RECEIVE_FILMS:
      return [...state, action.films];
    default:
      return state;
  }
}

reducers/index

import { combineReducers } from 'redux';
import { films } from './FilmsReducer';

export default combineReducers({
  films,
});

containers/FilmListContainer

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchFilmsRequest } from '../actions';
import FilmList from '../components/FilmList'

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

  componentWillMount() {
    this.props.fetchFilmsRequest();
  }

  render() {
    return (
      <div>
        <FilmList films={this.props.films}/>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  films: state.films
})

export default connect(mapStateToProps, {fetchFilmsRequest: fetchFilmsRequest})(FilmListContainer);

configureStore.js

import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';

export default function configureStore(initialState) {
    const composeEnhancers =
        window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ?
            window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
                // options like actionSanitizer, stateSanitizer
            }) : compose;

    const enhancer = composeEnhancers(
        applyMiddleware(thunk)
    );

    return createStore(
        rootReducer,
        initialState,
        enhancer
    );
}

如前所述,Redux DevTools会在有效负载中显示影片,但影片仍保持0状态。 有人能指出我正确的方向吗?

亲密无间,您的动作需要通过调度一个事件来将数据发送到商店,然后由您的reduce可以捕获该事件。 这是使用分派对象上的type属性完成的。

https://redux.js.org/basics/actions

return fetch('https://www.snagfilms.com/apis/films.json?limit=10')
  .then(response => {
    dispatch({
      type: RECEIVE_FILMS,
      payload: response,
    })
  })

然后,您需要在减速器中获取数据并将其放入存储中

export function films (state = [], action) {
  switch (action.type) {
    case RECEIVE_FILMS:
      return { 
        ...state,
        films: action.payload.films
      };
    default:
      return state;
  }
}

只需按以下方式调度已解决的fetch承诺的结果:

如果有效载荷是json,则:

export const fetchFilmsRequest = () => {
  return dispatch => {
    return fetch('https://www.snagfilms.com/apis/films.json?limit=10')
      .then(response => response.json())
      .then(response => {
        dispatch({
          type: RECEIVE_FILMS,
          payload: response
        })
      })
  }

您的减速器需要稍作修改以:

export function films (state = [], action) {
  switch (action.type) {
    case RECEIVE_FILMS:
      return [...action.payload]; // assuming response is jus array of films
    default:
      return state;
  }
}

看起来您只需要使用命名的导入(而不是默认的导出)将动作类型常量导入到reducer中即可。

import {RECEIVE_FILMS} from '../actions'而不是import RECEIVE_FILMS from '../actions'

您可以通过订阅store并使用store.getState()获得更新状态。

脚步:

  1. 在组件类的构造函数中编写订阅函数。
  2. 通过store.getState()设置类的状态。

从“ ../js/store/index”导入商店;

类MyClass扩展了Component {

构造函数(属性,上下文){

 super(props, context);

 this.state = {

        classVariable: ''

 }
 store.subscribe(() => {

    this.setState({

    classVariable: store.getState().MyStoreState.storeVariable

    });

 });

}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM