Redux状态不更新/重新渲染

时间:2016-07-07 19:13:38

标签: reactjs rendering state redux updating

我有一个带有动作创建者的组件,在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();
}

.... 

2 个答案:

答案 0 :(得分:3)

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

编辑:

如果该组件为connect,则dispatch中可以使用this.props

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

答案 1 :(得分:1)

根据Scarysize的建议,我使用了派遣。

我收到了错误:

ivyJob

所以我改用了它:

Component.js

dispatch(this.props.fetchPhotots())
相关问题