This is the fourth day of my participation in the August More text Challenge. For details, see: August More Text Challenge.
Story – thunk is introduced
Redux-thunk can be used to delay the dispatch of actions, which can handle the dispatch of asynchronous actions.
Install NPM I --save-dev redux-thunkCopy the code
1. Use applyMiddleware and redux-thunk in Reducers’ index.js
import {createStore,combineReducers,applyMiddleware} from 'redux'
import counterReducer from './count'
import thunk from 'redux-thunk'
import loginReducer from './user'
// 3. Storage in the warehouse
let store = createStore(combineReducers({
counter: counterReducer,
user: loginReducer
}),applyMiddleware(thunk))
export default store
Copy the code
2. Change dispatch from synchronous to asynchronous, and we can get all the states in the redux
// this.props.dispatch(actions.counter.incCount({count: ++this.num}))
// Send through thunk
this.props.dispatch((dispatch,getState) = >{
dispatch(actions.counter.incCount({count: + +this.num}))
console.log(getState(),'Obtain methods... ')})Copy the code
Results the following
Second, the Axios
1. Introduction to Axios
Axios is a promise-based library that runs in both the browser and node environments. The vUE official development team dropped maintenance of their official library, Vue-Resource, and went straight to axios.
1.Install NPM I -- Save AxiosCopy the code
2. Use of Axios GET requests in React
import axios from "axios";
componentDidMount() {
axios.get('http://vueshop.glbuys.com/api/home/index/nav?token=1ec949a15fb709370f')
.then(res= > {
console.log(res,'data... ')})}Copy the code
Render the data to the page
axios.get('http://vueshop.glbuys.com/api/home/index/nav?token=1ec949a15fb709370f')
.then(res= > {
console.log(res,'data... ')
if(res.data.code === 200) {
this.setState({
navs: res.data.data})}}) <ul> {this.state.navs.map((v,i) = > {
return (
<li key={i}>{v.title}</li>
)
})
}
</ul>
Copy the code
3. Axios post requests are used in React
Login interface is generally X-wwW-form-Urlencoded format parameters, this is to be compatible with IE, we can use urlSearchParams can also install QS
let params = new URLSearchParams()
params.append('cellphone'.this.state.username)
params.append('password'.this.state.password)
axios.post('http://vueshop.glbuys.com/api/home/user/pwdlogin?token=1ec949a15fb709370f',params)
.then(res= > {
if(res.data.code === 200) {
this.props.dispatch((dispatch) = >{
dispatch(actions.user.login( {username: this.state.username, isLogin: true}))
this.props.history.go(-1); })}else {
alert(res.data.data)
}
console.log(res)
})
Copy the code