【问题标题】:Redux State Not Updating/RerenderingRedux 状态未更新/重新渲染
【发布时间】:2016-07-07 19:13:37
【问题描述】:

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

我可以在 redux 中看到新数据的唯一方法是转到另一个页面。那时我可以看到 filterPhotos 存储有数据。如何立即渲染 store 中的新数据?

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;
}

动作索引.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"");
    });
  }
}

组件.js

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

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

.... 

【问题讨论】:

    标签: reactjs rendering state redux updating


    【解决方案1】:

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

    编辑:

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

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

    【讨论】:

    • 我又试了一次,它说dispatch没有定义,我需要在组件中提到dispatch吗?这是我在 mapStateToProps、mapDispatchToProps)(Component.js) 之前所拥有的,我在其中引用了函数 mapDispatchtoProps
    【解决方案2】:

    按照 Scarysize 的建议,我使用了 dispatch。

    我遇到了一个错误:

    dispatch(this.props.fetchPhotots())
    

    所以我改用这个:

    组件.js

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 2019-05-07
      • 2020-07-26
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多