【发布时间】:2019-12-26 17:28:22
【问题描述】:
一般的想法是有人点击按钮,动作从服务器获取数据并调度它。状态正在更新,页面上的内容正在改变。动作看起来完全像这样:
export function getPosts(page){
return function(dispatch){
axios.get(`${ROOT_URL}/home?page=${page}`)
.then(response => {
dispatch ({
type: FETCH_POSTS,
payload: response.data
})
})
.catch((error) => {
console.log(error)
});
}
}
Reducer 非常简单:
export default function(state={}, action){
switch(action.type){
case FETCH_POSTS:
return {posts: action.payload, ...state};
}
return state;
}
主页看起来就是这样:
import React, { Component } from 'react';
import * as actions from '../actions';
import RequireAuth from './auth/require_auth';
import { connect } from 'react-redux';
import { compose } from 'redux';
class Home extends Component {
constructor(props) {
super(props);
this.state = {
posts: 'loading....',
};
this.props.getPosts();
}
handlePage(){
console.log(this.props);
let page = 3;
this.props.getPosts();
}
componentWillReceiveProps(nextProps){
let posts = nextProps.posts.posts.map((post) => {
return (<li key={post._id}>{post.date}</li>)
});
this.setState({posts: posts});
}
shouldComponentUpdate(nextState, nextProps){
console.log(nextProps.posts, nextState.posts);
return true;
}
render(){
return(
<div>
{this.state.posts}
<button onClick={this.handlePage.bind(this)}>change something</button>
</div>
)
}
}
function mapStateToProps(state){
return {posts: state.post}
}
export default connect(mapStateToProps, actions)(Home);
我原以为状态会在 componentWillReciveProps 中更新,但事实并非如此。数据将在一段时间后被获取,所以我不能像那样设置状态。知道怎么做吗?
【问题讨论】:
标签: javascript reactjs redux