Когда я обновляю Redux через компонент, само хранилище не обновляется мгновенно, а с задержкой. Почему так происходит? Использую react-starter-kit/redux
class ArticleList extends Component {
constructor(props) {
super(props);
this.props = props;
}
componentWillMount() {
let { reduxKey, articles, actions } = this.props; // key in redux storage
this.props.actions.initAll(reduxKey); // init key in redux; to prevent errors
let store = this.props.store[reduxKey]; // current storage in redux
// pass mainkey in context also
this.store = store;
console.log("inComponent: ", store, this.props.store);
setTimeout(function () {
console.log("setTimeout: ", this.props.store, store)
}.bind(this), 0)
}
async load() {
return await this.props.actions.fetchArticles(this.props.query, this.props.key, this.store.latest + 10);
}
render() {
// ...
}
}
export default connect(state => ({
store: state.article
}),
(dispatch) => ({
actions: bindActionCreators(articleActions, dispatch)
})
)(ArticleList);
Его вызов:
<div>
<ArticleList reduxKey="home" query="filter[tag__not_in]=44" articles={this.props.articles}/>
</div>
<div>
<ArticleList reduxKey="recent" query="" articles={[]}/>
</div>
<div>
<ArticleList reduxKey="life" query="filter[cat]=6" articles={[]}/>
</div>
Reducer:
import { UPDATE_ARTICLE } from '../actions/article';
export default function runtime(state = {}, action) {
const { type, tag, articles = [], latest = 1, loading = false, max = 999 } = action;
switch (type) {
case UPDATE_ARTICLE:
console.log("State before: ", state);
let arts = state[tag] ? state[tag] : { articles: [] };
arts = {
articles: [
...arts.articles,
...articles,
],
latest,
loading,
max
};
console.log("State after: ", state);
return {
...state,
[tag]: arts
};
default:
return state;
}
}
Action:
import fetch from '../core/fetch';
export const UPDATE_ARTICLE = "article.update";
export function setArticles(tag, articles, latest, loading, max) {
return {
type: UPDATE_ARTICLE,
tag,
articles,
latest,
loading,
max
}
}
export function initAll (tag) {
return (dispatch) => (dispatch(setArticles(tag, [], 1, false, null)))
}
export function fetchArticles (filter, tag, latest) {
return async (dispatch) => {
let page = latest / 10;
dispatch(setArticles(tag, [], latest, true, null)); // set loading indicator
const resp = await fetch("http://local.dev/wp-json/wp/v2/posts?fields=categories,date,short,title,id&per_page=10&"+filter + "&page=" + (latest / 10), {
method: 'get',
headers: {
Accept: 'application/json'
},
credentials: 'include',
})
const data = await resp.json();
dispatch(setArticles(tag, data, latest, false, resp.headers.get("X-WP-Total"))); // dispatch action
return data;
}
}