使用React,Redux,Redux-thunk我想有通过服务器请求(API调用)的初始状态,但我似乎无法得到这个工作.
到目前为止我得到了什么:
var Redux = require('redux');
var carReducer = require('./reducers/cars');
var thunk = require('redux-thunk').default;
var initialState = require('./reducers/initialState');
var rootReducer = Redux.combineReducers({
cars: carReducer
});
module.exports = Redux.applyMiddleware(thunk)(Redux.createStore)(rootReducer, initialState.loadInitial());
Run Code Online (Sandbox Code Playgroud)
这是我最初的商店创作.我InitialState看起来像这样:
var $ = require('jquery');
module.exports = {
loadInitial: loadInitial
};
function loadInitial() {
return {
cars: [
{}
]
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试将其loadInitial转换为a时$.get('api/...'),Redux告诉我,我需要一个初始状态才能使其工作.
在我的reducer中我有一个加载方法:
function updateReducer(state, action) {
switch (action.type) {
case 'load':
return action.data;
case 'update':
return updateCars(action.data, …Run Code Online (Sandbox Code Playgroud) 我试图了解(v5)包和之间的区别,BrowserRouter以及Router对react-router-dom下面的示例有什么区别。
该文件说:
BrowserRouter A,使用HTML5历史记录API(pushState,replaceState和popstate事件)使UI与URL保持同步。
来源:https : //reacttraining.com/react-router/web/api/BrowserRouter
路由器 所有路由器组件的通用底层接口。通常,应用将使用高级路由器之一代替:BrowserRouter,HashRouter,MemoryRouter,NativeRouter,StaticRouter
来源:https : //reacttraining.com/react-router/web/api/Router
据我了解,我应该为HTML5浏览器应用程序使用BrowserRouter,到目前为止,我一直在这样做。
history.push(...)示例:
我正在尝试history.push('/myNewRoute')在一个大块内执行一个:
import history as './history';
...
export function someAsyncAction(input) {
return dispatch => {
fetch(`${API_URL}/someUrl`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ input }),
}).then(() => {
history.push('/myNewRoute');
}).catch((err) => {
dispatch(setError(err));
})
};
};
Run Code Online (Sandbox Code Playgroud)
history 定义为此模块:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
Run Code Online (Sandbox Code Playgroud)
并且history还将传递到我的路由器: …
html5-history reactjs react-router react-thunk react-router-dom
我正在为多频道聊天应用创建一个React/Redux前端.我有得到一些问题,反应的组分,同时使用状态改变后重新渲染redux,react-redux和redux-thunk.
我相信我的减速器是非变异的,而且我是通过它订阅react-redux的connect.当我运行应用程序并查看浏览器控制台时,我看到组件的初始渲染(即具有初始,空状态),然后状态更改(由操作调度触发index.js)....我会期望组件使用新道具重新渲染,但它不会发生.
我在这里张贴了一个回购:https: //github.com/mattmoss/react-redux-no-update
node_modules不在repo中,所以要运行,首先下载依赖项(运行yarn就足够了),然后npm start.
一些摘录(请参阅回购中的完整资料):
reducers/channelList.jsimport * as c from '../actions/constants';
export default function channelList(state = [], action) {
switch (action.type) {
case c.FETCH_CHANNELS_SUCCESS:
return action.channels;
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
actions/channelActions.jsexport function fetchChannels() {
return (dispatch) => {
return ChannelApi.allChannels()
.then(channels => dispatch(fetchChannelsSuccess(channels)))
.catch(error => { throw(error); });
};
}
export function fetchChannelsSuccess(channels) {
return { …Run Code Online (Sandbox Code Playgroud) 我是整个 React Redux 世界的新手,但我想我现在知道 Redux 是如何工作的。然而现在我面临着一个新的挑战,我需要实现异步数据获取。我选择使用 axios 作为我的 http 客户端。
我现在遇到的问题是我已经阅读了有关 redux async thunk 的内容,但我不知道何时以及为什么要使用它。据我所知,它向 redux 添加了中间件,可以处理 async/await 和 Promise。
我想简单地使用axios来获取数据,然后使用dispatch来存储它们。像这样
const loadData = async () => {
const res = await axios.get('https://www.api.com/mydata');
const data = res.data;
dispatch(setMyData(data));
}
Run Code Online (Sandbox Code Playgroud)
createAsyncThunk对此有何帮助?
用例:我有一个用 JHipster 生成的 React 应用程序。我需要从 API 获取数据,映射到表单合同,然后提交表单。
问题:JHipster 生成的减速器代码不返回承诺,那么我如何知道减速器操作何时完成?获取实体更新状态后如何调用函数?
获取实体并返回 ICrudGetAction:
export interface IPayload<T> { // redux-action-type.ts (JHipster Code from node_modules)
type: string;
payload: AxiosPromise<T>;
meta?: any;
}
export type IPayloadResult<T> = ((dispatch: any) => IPayload<T> | Promise<IPayload<T>>);
export type ICrudGetAction<T> = (id: string | number) => IPayload<T> | ((dispatch: any) => IPayload<T>);
// Start of my reducer code
export default (state: AdState = initialState, action): AdState => {
switch (action.type) {
case REQUEST(ACTION_TYPES.FETCH_MYENTITY_LIST):
return {
...state,
errorMessage: null,
updateSuccess: …Run Code Online (Sandbox Code Playgroud) 我正在使用react native + redux + redux-thunk我对redux并没有太多的经验
我正在组件内部调用动作。
this.props.checkClient(cliente);
if(this.props.clienteIsValid){
...
}
Run Code Online (Sandbox Code Playgroud)
在该操作中,将调用一个需要花费几秒钟的api。
export const checkClient = (cliente) => {
return dispatch => {
axios.get(`${API_HOST}/api/checkclient`, header).then(response => {
dispatch({type: CHECK_CLIENT, payload: response.data }); //valid or invalid
}).catch((error) => { });
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在api响应完成之前将动作的返回延迟?我需要api响应才能知道客户端有效还是无效。也就是说,我需要解决该操作,然后验证客户端有效或无效。
我有从我的组件调用异步操作的问题,我想我做了所有工作所需的一切,但似乎没有,我用过:
mapDispatchToProps
在里面我回来了
actions:bindActionCreators(fetchPosts,dispatch)
我连接它.
在所有这些事情之后,我尝试在我的组件中调用此操作 -
this.props.actions.fetchPosts()
结果我在控制台中收到此错误 -
this.props.actions.fetchPosts不是一个函数
我无法理解它的问题是什么,因为我做了所有事情,这里将是完整的来源:
零件
import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Home.css';
import { fetchPosts } from '../actions/counter';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
class Home extends Component {
constructor(props) {
super(props)
}
render() {
return (
<div>
<div className="container">
<div className="banner_animated">
<p> dadasda</p>
</div>
</div>
<div className="container-fluid">
<div className="center">
<input type="text"/>
<button className="btn-2 btn-2a btn" …Run Code Online (Sandbox Code Playgroud) 容器组件
import { connect } from 'react-redux';
import { signUpUser } from '../actions/userActions';
import Register from '../components/register';
function mapStateToProps(state) {
return {
user: state.user
};
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Register);
Run Code Online (Sandbox Code Playgroud)
登记表
import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router-dom';
import { reduxForm, Field, SubmissionError } from 'redux-form';
import { signUpUser } from '../actions/userActions';
//Client side validation
function validate(values) {
var errors = {}; …Run Code Online (Sandbox Code Playgroud) react-thunk ×8
reactjs ×8
react-redux ×4
redux ×4
javascript ×2
asynchronous ×1
jhipster ×1
middleware ×1
react-async ×1
react-native ×1
react-router ×1