事实证明,Redux 对我来说有点难以理解,我想知道是否有人可以帮助我指出正确的方向,以获取我想要的结果。只是一个预警:我正在使用 ES6 语法。
好的,我已经设置了一些沙箱来测试 redux 的工作原理,这是我正在使用的当前文件设置。
-actions
--index.js
-reducers
--index.js
--reducer_user.js
-containers
--ReduxTest.js
在我的容器 ReduxTest.js 中,我有以下代码。
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchUser } from '../actions/index';
class ReduxTest extends Component {
render() {
return (
<div>
{console.log(this.props.fetchUser())}
{console.log(this.props.user)}
</div>
)
}
}
export default connect( null, { fetchUser } ) (ReduxTest);
当我将 Redux Test.is 渲染到屏幕上时,第一个 console.log 语句显示为:
Object { type: "FETCH_USER", payload: "This is just a test."}
然而,第二个显示为“未定义”。
这是我的操作 index.js 的样子,
export const FETCH_USER = 'FETCH_USER';
export function fetchUser() {
const testing = "This is just a test.";
return {
type: FETCH_USER,
payload: testing
}
}
这是我的 reducer_user.js 文件
import { FETCH_USER } from '../actions/index';
export default function(state = null, action) {
switch(action.type) {
case FETCH_USER:
return action.payload;
}
return state;
}
and finally,这是我的reducer文件夹中的index.js
import { combineReducers } from 'redux';
import UserReducer from './reducer_user';
const rootReducer = combineReducers({
user: UserReducer
});
export default rootReducer;
我正在使用 Udemy 的视频教程,因此我可以从中了解一些语法以及其他语法。我的印象是我能够从index.js减速器访问“this.props.user”,但我做错了什么,或者错过了一个步骤。任何帮助,将不胜感激。
我很清楚,我的目的是成功地让 ReduxTest 容器控制台仅记录有效负载中的字符串。如果你能帮忙的话,我想我可以从那里继续下去。谢谢=)