tus*_*ior 5 javascript reactjs redux
总体思路是,有人单击按钮,操作从服务器获取数据并发送它。状态正在更新,页面上的内容正在发生变化。该动作看起来完全像这样:
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)
});
}
}
Run Code Online (Sandbox Code Playgroud)
减速器非常简单:
export default function(state={}, action){
switch(action.type){
case FETCH_POSTS:
return {posts: action.payload, ...state};
}
return state;
}
Run Code Online (Sandbox Code Playgroud)
主页看起来就像这样:
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);
Run Code Online (Sandbox Code Playgroud)
我以为状态会在 componentWillReciveProps 中更新,但这并没有发生。数据将在一段时间后获取,因此我无法像那样设置状态。知道如何做到这一点吗?
对于异步操作,有两种可能的方式:
status标志工作流程希望:
status为'fetching'status为'success'status为'error'进一步阅读:Redux :: 异步操作
| 归档时间: |
|
| 查看次数: |
6943 次 |
| 最近记录: |