在Redux中将文本推送到数组
我试图使用Redux将一些文本推送到数组中,但遇到了问题。在我复制了我的状态后,我不确定该怎么办。另外,我只想确认我应该将我的在Redux中将文本推送到数组,redux,react-redux,Redux,React Redux,我试图使用Redux将一些文本推送到数组中,但遇到了问题。在我复制了我的状态后,我不确定该怎么办。另外,我只想确认我应该将我的appState导入我的reducer store.js import {createStore} from 'redux'; import rootReducer from './reducers/index'; export const appState = { links: [] }; const store = createStore(rootRedu
appState
导入我的reducer
store.js
import {createStore} from 'redux';
import rootReducer from './reducers/index';
export const appState = {
links: []
};
const store = createStore(rootReducer, appState);
export default store;
reducers/index.js
import {appState} from '../store';
function addLink(state = appState, action) {
switch(action.type) {
case 'ADD_LINK':
const linkName = action.linkName;
console.log('Adding link');
console.log(linkName);
console.log(appState);
return {
...state.splice(),
// Now what?
};
default:
return state;
}
};
export default addLink;
您不需要导入
appState
。假设state只是一个数组,您的方法应该如下所示
function addLink(state = {links: []}, action) {
switch(action.type) {
case 'ADD_LINK':
const linkName = action.linkName;
console.log('Adding link');
console.log(linkName);
console.log(appState);
return {
...state,
links: [linkName, ...state.links]
};
default:
return state;
}
};
您不需要导入
appState
。假设state只是一个数组,您的方法应该如下所示
function addLink(state = {links: []}, action) {
switch(action.type) {
case 'ADD_LINK':
const linkName = action.linkName;
console.log('Adding link');
console.log(linkName);
console.log(appState);
return {
...state,
links: [linkName, ...state.links]
};
default:
return state;
}
};
好的,谢谢!但它并没有更新我的商店状态<代码>链接仍然是一个空数组:(您需要在DOM的顶部插入存储。
类似的内容。@staxwell我更新了代码。试试看。您的初始状态与您要求的操作不匹配。好的,谢谢!但它不会更新我的存储状态。链接
仍然是一个空数组:(您需要将存储注入DOM顶部。
类似的内容。@staxwell我更新了代码。请尝试。您的初始状态与您要求的操作不匹配。