这个问题已经被问过好几次了,但是我并不真正理解我找到的答案。使用 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,任何库都是好的。
关于reactjs - 我应该如何使用 "redux-thunk"作为异步初始状态? ( react /还原),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38907458/