Redux 状态不是 Updating/Rerendering

Redux State Not Updating/Rerendering

我有一个带有动作创建器的组件,它在 componentWillMount 上检索数据,然后将其存储在 redux 属性 中。我的问题是检索到的数据没有放在 filteredPhotos redux 存储中。

我可以在 redux 中看到新数据的唯一方法是转到另一个页面。那时我可以看到包含数据的 filteredPhotos 存储。如何立即在商店中呈现新数据?

Reducer.js

import { 
    PHOTOS
} from '../actions/types';


const INITIAL_STATE = {  filteredPhotos:[] };

export default function(state = INITIAL_STATE, action) {
  switch (action.type) {
    case PHOTOS:
        console.log("THIS IS THE NEW DATA");
        console.log(action.payload.data);
      return {...state, filteredPhotos: action.payload.data};
  }
  return state;
}

操作index.js

import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';

import ImageReducer from './Reducer.js';

const rootReducer = combineReducers({
  images: ImageReducer
});

export default rootReducer;

action.js

import axios from 'axios';
const API_URL = 'http://jsonplaceholder.typicode.com/photos'; 

import {
  PHOTOS,
} from './types';


export function fetchPhotos() {
  return function(dispatch) {
    axios.get(`${API_URL}`, {withCredentials: true})
    .then(response => {
      dispatch({
        type:PHOTOS,
        payload: response
      });
    })
   .catch(() => {
      console.log("Not working"");
    });
  }
}

Component.js

class Test extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      testing:false,
    };
  }

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

.... 

componentWillMount() 你需要 dispatch(this.props.fetchPhotots())。否则动作创建者将无法访问 dispatch(假设你也在使用 redux-thunk 中间件)

编辑:

如果组件是 connected,则 dispatchthis.props 中可用:

const {dispatch, fetchPhotos} = this.props;
dispatch(fetchPhotos());

听从 Scarysize 的建议,我使用了 dispatch。

我遇到了一个错误:

dispatch(this.props.fetchPhotots())

所以我改用了这个:

Component.js

function mapDispatchToProps(dispatch){
  return bindActionCreators({ fetchPhotos }, dispatch);
}