根据文档,"没有中间件,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) 说我有以下内容:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
}
}
Run Code Online (Sandbox Code Playgroud)
在该动作创建者中,我想访问全局存储状态(所有reducers).这样做更好:
import store from '../store';
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return {
type: SOME_ACTION,
items: store.getState().otherReducer.items,
}
}
Run Code Online (Sandbox Code Playgroud)
或这个:
export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
return (dispatch, getState) => {
const {items} = getState().otherReducer;
dispatch(anotherAction(items));
}
}
Run Code Online (Sandbox Code Playgroud) 是否可以在减速机本身发送动作?我有一个进度条和一个音频元素.目标是在音频元素中更新时间时更新进度条.但是我不知道将ontimeupdate事件处理程序放在何处,或者如何在ontimeupdate的回调中调度一个动作来更新进度条.这是我的代码:
//reducer
const initialState = {
audioElement: new AudioElement('test.mp3'),
progress: 0.0
}
initialState.audioElement.audio.ontimeupdate = () => {
console.log('progress', initialState.audioElement.currentTime/initialState.audioElement.duration);
//how to dispatch 'SET_PROGRESS_VALUE' now?
};
const audio = (state=initialState, action) => {
switch(action.type){
case 'SET_PROGRESS_VALUE':
return Object.assign({}, state, {progress: action.progress});
default: return state;
}
}
export default audio;
Run Code Online (Sandbox Code Playgroud) 我意识到这是一个基本问题,但我没有在其他地方找到答案.
是store.dispatch同步还是异步Redux?
如果它是异步的,有可能在动作传播之后添加回调,因为它可以用React?
我读到Redux Thunk是管理异步操作/请求的可靠方法.没有太多关于通过其他行动调度行动的事情.
如何调度同步动作?我不确定thunk方法的性能问题,但是我可以在其他动作创建者中调度动作而不在其中定义函数吗?
在我看来,使用redux thunk对于这种需求是不必要的.
我不明白需要什么redux-thunk.据我所知,a thunk是一个返回函数的函数.在我看来,包装的表达式和中间件的使用可以做更多的工作来模糊正在发生的事情.取自redux-thunk的示例代码
import thunk from 'redux-thunk';
// Note: this API requires redux@>=3.1.0
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
// Meet thunks.
// A thunk is a function t hat returns a function.
// This is a thunk.
function makeASandwichWithSecretSauce(forPerson) {
// Invert control!
// Return a function that accepts `dispatch` so we can dispatch later.
// Thunk middleware knows how to turn thunk async actions into actions.
return function (dispatch) {
return fetchSecretSauce().then(
sauce …Run Code Online (Sandbox Code Playgroud) 我正在使用isomorphic fetch创建API请求,并使用Redux来处理我的应用程序的状态.
我想通过触发Redux操作来处理互联网连接丢失错误和API错误.
我有以下(工作进行中/坏)代码,但无法找出触发Redux操作的正确方法(而不是仅抛出错误并停止所有操作):
export function createPost(data = {}) {
return dispatch => {
dispatch(requestCreatePost(data))
return fetch(API_URL + data.type, {
credentials: 'same-origin',
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-WP-Nonce': API.nonce
},
body: JSON.stringify(Object.assign({}, data, {status: 'publish'}))
}).catch((err) => {
//HANDLE WHEN HTTP ISN'T EVEN WORKING
return dispatch => Promise.all([
dispatch({type: PRE_FETCH_RESOURCES_FAIL, errorType: 'fatal', message:'Error fetching resources', id: h.uniqueId()}),
dispatch({type: PRE_CREATE_API_ENTITY_ERROR, errorType: 'fatal', id: h.uniqueId(), message: 'Entity error before creating'})
])
}).then((req) => {
//HANDLE RESPONSES THAT CONSTITUTE AN …Run Code Online (Sandbox Code Playgroud) 我有一些不直接操纵我的应用程序状态的ajax请求.在react/redux应用程序中,为这些ajax请求分派动作是否必要(或有任何好处),而不是直接在组件中发送ajax请求?
为了简化我的场景,我基本上有一个我的redux状态的对象列表.我正在使用表单将新对象发布到数据库,成功发布后,我将重定向到发送GET请求的列表页面,并获取列表并更新状态.
发布新对象的AJAX调用并不直接操纵我的状态.
我与通过完整的3步Redux的异步去工作队步骤例如:'FETCH_REQUESTED','FETCH_SUCCESS','FETCH_FAIL'连同所有的AJAX请求相应的减速,这是一个很大的麻烦,以增加更多的,似乎在减速不会是有道理的.
几个月以来,我一直在使用React,Redux.生态系统中最令人困惑的部分之一是异步数据流.有很多很好的解决方案,为您的问题选择合适的解决方案是困难的部分.
在我的应用程序中,动作创建者大多数都有异步axios [ajax]调用我的后端apis.将Redux-Promise注入中间件可以解决异步数据流的问题.
考虑到可扩展的应用程序,我可能需要在我的动作创建者中链接多个axios调用.我想我仍然可以使用Redux-Promise作为中间件,这将在我的应用程序中处理异步数据流.
一般来说,团队更倾向于使用Redux-Thunk,我觉得这个问题的语法更复杂.考虑到我的大多数动作创建者只进行了axios调用(promises),我需要在评估这两个框架时提出建议.我见过的讨论了大量的终极版-咚这里.我明白thunk是如何有用的..但是当我只使用Promises时,我需要更多的澄清来评估Redux-Promise和Redux-Thunk.哪种中间件在这种情况下更好?为什么?使用Redux-Thunk而不是Redux-Promise可以获得哪些优势?或者没有?
我对整个react-native/redux世界都很陌生,也许这个问题听起来很愚蠢:)
我知道对于API调用或类似的东西,惯例是通过中间件来做到这一点,但它总是必要的(它增加了很多样板).
我成功地在reducer中添加了异步方法来管理设备API连接,例如In-App或Local Notifications,但我想知道以这种方式处理它是否可行.
例如在我的reducer中有这样的方法:
function initInApp(state, itemSkus){
init(state, itemSkus);
return {
...state,
itemSkus: itemSkus,
}
}
Run Code Online (Sandbox Code Playgroud)
而这个管理异步部分:
async function init(state, itemSkus){
try {
if( !state.isInit ){
const prepare = await Promise.all(RNIap.prepareAndroid());
return{
...state,
isInit: true,
errorCode: false,
}
}
else {
return ...state;
}
} catch (errorCode) {
return{
...state,
isInit: false,
errorCode: errorCode,
itemSkus: itemSkus
}
}
}
Run Code Online (Sandbox Code Playgroud)
也许它在性能方面效率不高或难以维护.你有什么想法?
谢谢 :)
redux ×9
javascript ×7
reactjs ×7
redux-thunk ×4
ajax ×1
asynchronous ×1
axios ×1
fetch ×1
react-native ×1
react-redux ×1
reducers ×1
typescript ×1