[英]How should I use “redux-thunk” for Async Initial state ? (react/redux)
这个问题已经被问了几次,但是我并没有真正理解我找到的答案。 使用React / Redux,我试图通过express将异步数据放入我的初始状态。 因为我习惯了d3,我的一个选择是使用“d3.json”...但如果它更好的话,我会很乐意使用别的东西。 从以前对同一主题的回答中,我添加了以下代码:
// redux action using a dispatcher (think middleware)
export function cool(url) {
return function(dispatch) {
return d3.json(url, response => {
dispatch(setData(response))
}
}
}
// redux action
export function setData(data) {
return {
type: 'DATA_CHART_ALL',
data
}
}
const authorDataReducer = (state = {}, action) => {
switch (action.type) {
case 'DATA_CHART_ALL':
return action.data
case 'DATA_CHART_FILTER':
return action.data
default:
return state;
}
};
export authorDataReducer;
起初我没有注意到它,但是从我最近的理解来看,上面的代码或多或少地遵循了redux-thunk
模式......所以从那里我尝试应用redux-thunk
但我无法做任何事情工作...
不确定我的问题是否清楚,能帮助减轻这一切是很好的。
谢谢。
你的问题不是很清楚,但我会尽力回答。 Redux-thunk是一种用于调度异步操作的中间件。 您在创建redux存储时初始化它:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
对于加载异步数据,即使它是初始状态,您也需要调度操作。 如果您正在使用react,则可以在安装了最高阶组件时执行此操作。
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { fetchTodos } from '../action';
import TodoList from './TodoList';
class App extends Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.props.fetchTodos();
}
render() {
return (
<TodoList
todos={this.props.todos}
/>
);
}
}
App.propTypes = {
todos: PropTypes.array.isRequired
};
const mapStateToProps = (state, ownProps) => ({
todos: state.todos
});
export default connect(
mapStateToProps,
{
fetchTodos: fetchTodos
}
)(App);
这将触发一个看起来像这样的动作
export const fetchTodos = () => {
return (dispatch) => {
return fetch(url).then((response) => {
disptach({
type: 'received_todos',
payload: {
response.json()
}
});
});
}
}
如你所见,我没有使用d3而是使用fetch 。 我猜任何图书馆都是好的,只要你回来了Promise。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.