我必須寫mapStateToProps
像下面寫`state.tree`,而不是`state.xxxReducer.tree`在`mapStateToProps`(反應終極版)
function mapStateToProps(state, ownProps) {
return {
node: ownProps.info? state.TreeNodeReducer.tree[ownProps.info.path] : {}
};
}
結合減速機:
import { combineReducers } from 'redux';
import TreeNodeReducer from './TreeNodeReducer'
const rootReducer = combineReducers({
TreeNodeReducer
});
export default rootReducer;
減速器/ TreeNodeReducer.js
import { OPEN_NODE, CLOSE_NODE, GET_NODES } from '../constants/NodeActionTypes';
const initialState = {
open: false,
info: {}
}
class NodeModel {
constructor(path, type, right) {
this.name = path;
this.path = path;
this.type = type;
this.right = right;
}
}
let lastId = 0;
function getFileList() {
var testNodes = []
for (var i=0; i< 3; i++) {
testNodes.push(new NodeModel(lastId,'d', i.toString()))
lastId++;
}
return testNodes
}
const getNodes = (state, action) => {
var { path } = action
var tree = state.tree ? state.tree : {}
tree[path] = getFileList(path)
return {
...state,
tree:tree
};
};
export default function (state = initialState, action) {
switch (action.type) {
case OPEN_NODE:
return { ...getNodes(state, action), open:true };
case GET_NODES:
return getNodes(state, action);
case CLOSE_NODE:
return {
...state,
open:false
};
default:
return state;
}
}
因爲state.TreeNodeReducer.tree
是一個全球性的狀態,它容納所有節點的信息,I W ant通過狀態直接訪問它。通過reducer的狀態返回將按reducer的名稱進行包裝,這對於簡單的項目並不方便。 Office doc不提供這種方式。任何想法?
PS:我不得不說我想繼續使用combineReducers
,我看到有些項目不使用它,直接通過reducer存儲可以達到我的目的但不好。
你能否也請顯示TreeNodeReducer? – Ashitaka
@Ashitaka我已經更新了代碼。 – Mithril