Redux状态不更新/重新渲染

问题描述:

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

.... 

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

按照Scarysize的建议,我用调度。

我得到了一个错误有:

dispatch(this.props.fetchPhotots()) 

所以我用这个代替:

Component.js

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