2016-07-07 304 views
0

我有一個動作創建器的組件,在componentWillMount上檢索數據,然後將其存儲在redux屬性中。我的問題是,檢索的數據沒有放在filteredPhotosredx存儲中。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(); 
} 

.... 

回答

3

componentWillMount()您需要dispatch(this.props.fetchPhotots())。否則,行動的創建者將無法獲得dispatch(假設你同時使用終極版 - thunk的中間件)

編輯:

如果組件是connect版則dispatch可在this.props

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

我再次嘗試這種方式,它說沒有定義調度,做我需要提及組件中的調度?這是我之前mapStateToProps,mapDispatchToProps)(Component.js),其中我引用了函數mapDispatchtoProps – lost9123193

1

按照Scarysize的建議,我用調度。

我得到了一個錯誤有:

dispatch(this.props.fetchPhotots()) 

所以我用這個代替:

Component.js

function mapDispatchToProps(dispatch){ 
    return bindActionCreators({ fetchPhotos }, dispatch); 
} 
相關問題