根据文档,"没有中间件,Redux商店只支持同步数据流".我不明白为什么会这样.为什么容器组件不能调用异步API,然后调用dispatch操作?
例如,想象一个简单的UI:字段和按钮.当用户按下按钮时,该字段将填充来自远程服务器的数据.
import * as React from 'react';
import * as Redux from 'redux';
import { Provider, connect } from 'react-redux';
const ActionTypes = {
STARTED_UPDATING: 'STARTED_UPDATING',
UPDATED: 'UPDATED'
};
class AsyncApi {
static getFieldValue() {
const promise = new Promise((resolve) => {
setTimeout(() => {
resolve(Math.floor(Math.random() * 100));
}, 1000);
});
return promise;
}
}
class App extends React.Component {
render() {
return (
<div>
<input value={this.props.field}/>
<button disabled={this.props.isWaiting} onClick={this.props.update}>Fetch</button>
{this.props.isWaiting && <div>Waiting...</div>}
</div>
); …Run Code Online (Sandbox Code Playgroud) 我对 redux 比较新。我已经阅读了很多文章,但我仍然没有清楚地了解使用的真正好处是什么redux-thunk。
我所理解的是它允许您返回一个函数而不是来自action-creators?的对象。但有什么好处呢?我在没有使用 redux-thunk 的情况下创建了一些小型 React 项目。
让我们考虑以下片段。两者的行为相同。
如果有人可以向我解释或向我指出正确的资源以更好地理解,那将会有很大的帮助。
With redux-thunk
export function fetchContacts(){
return function(dispatch){
axios
.get('/contacts')
.then( contacts => dispatch({ type: 'FETCH_CONTACTS', payload: contacts}))
}
}Run Code Online (Sandbox Code Playgroud)
Without redux-thunk
const client = axios.create({
baseURL: "http://localhost:3000",
headers: {
"Content-Type": "application/json"
}
})
const url = '/contacts';
export function fetchContacts(){
return {
type: 'FETCH_CONTACTS',
payload: client.get(url)
}
}Run Code Online (Sandbox Code Playgroud)