所以我一直在努力找出react-redux生态系统一段时间了。我几乎就在那里,但仍有一些东西不断给我是问题,那就是componentDidUpdate方法。当我发送异步操作时,正确调用存储是reducer,并且组件的状态会更新。
但由于某种原因,componentDidUpdate方法没有触发,没有重新渲染,我无法访问更新的道具。如果我是console.log(this.props.blogStore),我可以在devtools中看到它的变化。首先它显示为一个空对象,但在点击时它会打开并显示更新后的状态。
我尝试了尽可能多的生命周期方法,但似乎没有任何效果,包括componentWillReceiveProps。
知道我做错了吗?
以下是代码:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import Datastore from 'Datastore';
const store = Datastore()
store.subscribe(() => console.log("state changed", store.getState()))
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
Datastore.js
import { combineReducers, createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk'
import Mainmenu from 'reducers/Mainmenu';
import Blogstore from 'reducers/Blogstore';
const reducer = combineReducers({
Mainmenu,
Blogstore,
})
export default function Datastore() {
const store = createStore(
reducer,
applyMiddleware(thunk)
)
return store
}
减速器
import Article from 'lib/Article';
import { ARTICLE_LOAD, ARTICLE_UPDATE, SAVE_ARTICLE_LIST } from 'actionTypes';
const initialBlogState = {
}
const Blogstore = (state=initialBlogState, action) => {
switch(action.type) {
case SAVE_ARTICLE_LIST:
state.init = true
state.articles = action.payload
return state
case ARTICLE_LOAD:
return state
case ARTICLE_UPDATE:
return state
}
return state
}
export default Blogstore;
博客-actions.js
import { ARTICLE_LOAD, ARTICLE_UPDATE, SAVE_ARTICLE_LIST } from 'actionTypes';
import APIFetch from '../lib/Fetch';
export function getArticlePids() {
return dispatch => {
APIFetch().get("/blog/list").then(response => {
dispatch({
type: SAVE_ARTICLE_LIST,
payload: response.data
})
})
}
}
组件
import React from 'react';
import { connect } from 'react-redux';
import * as blogActions from '../actions/blog-actions';
@connect(state => ({
blogStore: state.Blogstore
}))
export default class Blog extends React.Component {
constructor() {
super()
}
componentDidMount() {
this.props.dispatch(blogActions.getArticlePids())
}
componentDidUpdate(prevProps) {
console.log("update", prevProps)
}
render() {
console.log("render", this.props.blogStore)
return (
<div><h1>Blog</h1></div>
)
}
}
这就是它。我不打算粘贴index.js和组件之间的App和Router,因为那里没有任何兴趣。只是一个基本的反应路由器和与此无关的组件。
答案 0 :(得分:4)
您需要从reducer中返回一个新对象,如下所示:
import Article from 'lib/Article';
import { ARTICLE_LOAD, ARTICLE_UPDATE, SAVE_ARTICLE_LIST } from 'actionTypes';
const initialBlogState = {
}
const Blogstore = (state=initialBlogState, action) => {
switch(action.type) {
case SAVE_ARTICLE_LIST:
return Object.assign({}, state, {
init: true,
articles: action.payload,
})
case ARTICLE_LOAD:
return state
case ARTICLE_UPDATE:
return state
}
return state
}
export default Blogstore;
否则,如果您尝试直接更新状态(正如您当前所做的那样),它只会改变状态的内部引用,并且反应组件将无法检测到更改并且不会重新呈现。 Read more here.