Commit
Install libraies
npm install --save redux react-redux axios redux-thunk
define get data api (jsonPlarceholder is a tool site for testing)
src/apis/jsonPlaceholder.js
import axios from 'axios';
export default axios.create({
baseURL: 'https://jsonplaceholder.typicode.com'
});
enable redux thunk for applying async operation
src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {createStore, applyMiddleware} from 'redux'
import { Provider } from 'react-redux'
import reducers from './reducers'
import thunk from "redux-thunk";
const store = createStore(reducers, applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store} >
<App />
</Provider>,
document.getElementById('root')
);
dispatch fetch data result in action creator
Reference if you feel "() => async dispatch =>" seems weird: https://www.isaacnote.com/2020/06/redux-shorten-async-function.html
src/actions/index.js
export const fetchPosts = () => async dispatch => {
console.log("action fetchPosts")
const response = await jsonPlaceholder.get('/posts')
dispatch({type:'FETCH_POSTS', payload: response})
}
define reducer to set up fetch result to state
src/reducers/index.js
export const fetchPostReducer = (fetchPosts = null, action) => {
console.log("fetchPostReducer", fetchPosts, action)
if (action.type === 'FETCH_POSTS') {
console.log("return action", action.payload.data)
return action.payload.data;
}
return fetchPosts
}
fetch data when mount component
src/components/PttPosts.js
import React, {Component} from "react";
import {connect} from 'react-redux'
import {fetchPosts, selectPttPost} from "../actions";
class PttPosts extends Component {
componentDidMount() {
console.log('fetch posts')
this.props.fetchPosts()
}
renderList() {
if (this.props.postList) {
console.log("renderList", this.props.postList)
return this.props.postList.map((post) => {
console.log("map", post)
return <div key={post.id}>
<div key={post.id}><a onClick={() => this.props.selectPttPost(post)}>Title:{post.title}</a></div>
</div>
});
} else {
return 'Loading...'
}
};
render() {
console.log('render', this.props)
return <div>{this.renderList()}</div>
}
}
const mapStateToProps = (state) => {
console.log("mapStateToProps",state)
return {postList: state.fetchPosts};
}
export default connect(mapStateToProps, { fetchPosts, selectPttPost })(PttPosts)
npm start and check result, can click item to show article
沒有留言:
張貼留言