刷新后数据从数组中消失
Data disappear from array after refresh
我有一个组件,我在其中异步添加数据,使用 mock post api 和 mirage js,它在 redux toolkit.Everythings 的异步 thunkn 中发送它的状态,效果很好,但主要思想是我发送到 redux thunk 的数据,reducer 我应该映射并在另一个组件中使用,一个技能栏。所以,我尝试将数据从 thunk 推入一个数组并导出 it.It 效果很好,每次我添加一个新项目时,它都会映射到组件中并呈现,但是当我刷新页面时,组件没有数据,但我需要在 refresh.My 应用程序连接到 redux 持久化后保持状态,但我发现这没有帮助,你知道可能是什么问题以及我应该如何解决它吗?
上面你看我mean.I输入了技能名称和技能范围,下面应该呈现为一个条,但是刷新后不保持状态..
应使用数据呈现的组件:
<div>
<ul className="skills">
{skillArray.map((skill, index) => <li
key={skill.name}
style={{ width: `${skill.level}%`}}
>
<p>{skill.name}<span>{skill.level}</span></p>
</li>
)}
</ul>
</div>
Slice,在 addNewSkill 操作中,我将数据推送到数组,并在上面的组件中使用:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'
// export const fetchSkills = createAsyncThunk(
// 'skills/fetchSkills',
// async (_, {rejectWithValue}) => {
// try{
// const response = await fetch('/api/skills',{
// method:'GET',
// })
// // console.log(response)
// if(!response.ok){
// throw new Error ('Server Error!');
// }
// const data = await response.json();
// // console.log(data)
// return data;
// } catch(error){
// return rejectWithValue(error.message);
// }
// }
// );
// export const addNewSkill = createAsyncThunk(
// 'educations/addNewSkill',
// async (text,range,{rejectWithValue,dispatch}) =>{
// try{
// const skill={
// name:text,
// range:range
// };
// const response = await fetch('/api/skills',{
// method:'POST',
// headers:{
// 'Content-name' : 'application/json',
// },
// body:JSON.stringify(skill)
// });
// if(!response.ok){
// throw new Error('Can\'t add skill. Server error')
// }
// const data = await response.json();
// dispatch(addSkill(data))
// }catch(error){
// return rejectWithValue(error.message);
// }
// }
// )
// const setError = (state, action) => {
// state.status = 'rejected';
// state.error = action.payload;
// }
// export const skillSlice = createSlice({
// name: 'skills',
// initialState: {
// name:null,
// range:null,
// status: null,
// error: null,
// },
// reducers: {
// addSkill: (state, action) => {
// state.name = action.payload?.name;
// state.range = action.payload?.range;
// },
// // },
// // extraReducers: {
// // [fetchSkills.pending]: (state, action) => {
// // state.status = 'loading';
// // state.error = null;
// // },
// // [fetchSkills.fulfilled]: (state, action) => {
// // state.status = 'resolved';
// // state.skillList = action.payload;
// // },
// // [fetchSkills.rejected]: setError,
// // },
// }}
// )
// export const { addSkill } = skillSlice.actions;
// // export const { addSkill } = skillSlice.actions
// export const selectSkill = (state) => state?.skills;
// export default skillSlice.reducer;
export const fetchSkills = createAsyncThunk(
'skills/fetchSkills',
async (_, {rejectWithValue}) => {
try{
const response = await fetch('/api/skills',{
method:'GET',
})
// console.log(response)
if(!response.ok){
throw new Error ('Server Error!');
}
const data = await response.json();
// console.log(data)
return data;
} catch(error){
return rejectWithValue(error.message);
}
}
);
const setError = (state, action) => {
state.status = 'rejected';
state.error = action.payload;
}
export const skillArray=[]
export const addNewSkill = createAsyncThunk(
'skills/addNewSkill',
async (skillData,{rejectWithValue,dispatch}) =>{
const {skillName,skillRange} = skillData
try{
const skill = {
name: skillName,
range: skillRange,
};
const response = await fetch('/api/skills',{
method:'POST',
headers:{
'Content-name' : 'application/json',
},
body: JSON.stringify(skill)
});
skillArray.push(skill)
if(!response.ok){
throw new Error('Can\'t add skill. Server error')
}
const data = await response.json();
dispatch(setSkill(data))
}catch(error){
return rejectWithValue(error.message);
}
}
)
export const skillSlice = createSlice({
name: "skills",
initialState: {
skills:[],
status: null,
error: null
},
reducers: {
setSkill: (state, action) => {
// console.log("action", action.payload);
// state.name = action.payload?.name;
// state.range = action.payload?.range;
state.skills.push(action.payload);
// localStorage.setItem(state.name,action.payload.range)
},
},
extraReducers:{
[fetchSkills.pending]:(state,action)=>{
state.status = 'loading';
state.error = null;
},
[fetchSkills.fulfilled]:(state,action)=>{
state.status = 'resolved';
state.name = action.payload;
},
[fetchSkills.rejected]: setError,
}
});
const { setSkill } = skillSlice.actions;
export const selectSkill = (state) => state?.skill;
export default skillSlice.reducer;
根目录:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import { persistStore, persistReducer } from 'redux-persist'
import { toggleButtonReducer } from './reducers/toggleButtonReducer'
import storage from 'redux-persist/lib/storage'
import thunk from 'redux-thunk'
import educationReducer from '../features/education/educationSlice';
import skillReducer from '../features/skills/skillSlice'
const rootReducer = combineReducers({
visibilityState: toggleButtonReducer,
educationState: educationReducer,
skills : skillReducer
})
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, rootReducer)
export const store = createStore(persistedReducer, composeWithDevTools(applyMiddleware(thunk)))
export const persistor = persistStore(store)
我想我解决了这个问题,如果这是一个好的方法,我想知道,但是我没有推送任何东西就直接访问了商店。
const skillList = useSelector((state)=>state.skills.skills)
console.log("skills",skillList)
并这样映射:
<ul className="skills">
{skillList.map((skill, index) => <li
key={skill.skills.name}
style={{ width: `${skill.skills.level}%`}}
>
<p>{skill.skills.name}<span>{skill.skills.level}</span></p>
</li>
)}
</ul>
我得到了预期的结果,这很好,但它是否是一个好的方法,我不知道。
我有一个组件,我在其中异步添加数据,使用 mock post api 和 mirage js,它在 redux toolkit.Everythings 的异步 thunkn 中发送它的状态,效果很好,但主要思想是我发送到 redux thunk 的数据,reducer 我应该映射并在另一个组件中使用,一个技能栏。所以,我尝试将数据从 thunk 推入一个数组并导出 it.It 效果很好,每次我添加一个新项目时,它都会映射到组件中并呈现,但是当我刷新页面时,组件没有数据,但我需要在 refresh.My 应用程序连接到 redux 持久化后保持状态,但我发现这没有帮助,你知道可能是什么问题以及我应该如何解决它吗?
上面你看我mean.I输入了技能名称和技能范围,下面应该呈现为一个条,但是刷新后不保持状态..
应使用数据呈现的组件:
<div>
<ul className="skills">
{skillArray.map((skill, index) => <li
key={skill.name}
style={{ width: `${skill.level}%`}}
>
<p>{skill.name}<span>{skill.level}</span></p>
</li>
)}
</ul>
</div>
Slice,在 addNewSkill 操作中,我将数据推送到数组,并在上面的组件中使用:
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'
// export const fetchSkills = createAsyncThunk(
// 'skills/fetchSkills',
// async (_, {rejectWithValue}) => {
// try{
// const response = await fetch('/api/skills',{
// method:'GET',
// })
// // console.log(response)
// if(!response.ok){
// throw new Error ('Server Error!');
// }
// const data = await response.json();
// // console.log(data)
// return data;
// } catch(error){
// return rejectWithValue(error.message);
// }
// }
// );
// export const addNewSkill = createAsyncThunk(
// 'educations/addNewSkill',
// async (text,range,{rejectWithValue,dispatch}) =>{
// try{
// const skill={
// name:text,
// range:range
// };
// const response = await fetch('/api/skills',{
// method:'POST',
// headers:{
// 'Content-name' : 'application/json',
// },
// body:JSON.stringify(skill)
// });
// if(!response.ok){
// throw new Error('Can\'t add skill. Server error')
// }
// const data = await response.json();
// dispatch(addSkill(data))
// }catch(error){
// return rejectWithValue(error.message);
// }
// }
// )
// const setError = (state, action) => {
// state.status = 'rejected';
// state.error = action.payload;
// }
// export const skillSlice = createSlice({
// name: 'skills',
// initialState: {
// name:null,
// range:null,
// status: null,
// error: null,
// },
// reducers: {
// addSkill: (state, action) => {
// state.name = action.payload?.name;
// state.range = action.payload?.range;
// },
// // },
// // extraReducers: {
// // [fetchSkills.pending]: (state, action) => {
// // state.status = 'loading';
// // state.error = null;
// // },
// // [fetchSkills.fulfilled]: (state, action) => {
// // state.status = 'resolved';
// // state.skillList = action.payload;
// // },
// // [fetchSkills.rejected]: setError,
// // },
// }}
// )
// export const { addSkill } = skillSlice.actions;
// // export const { addSkill } = skillSlice.actions
// export const selectSkill = (state) => state?.skills;
// export default skillSlice.reducer;
export const fetchSkills = createAsyncThunk(
'skills/fetchSkills',
async (_, {rejectWithValue}) => {
try{
const response = await fetch('/api/skills',{
method:'GET',
})
// console.log(response)
if(!response.ok){
throw new Error ('Server Error!');
}
const data = await response.json();
// console.log(data)
return data;
} catch(error){
return rejectWithValue(error.message);
}
}
);
const setError = (state, action) => {
state.status = 'rejected';
state.error = action.payload;
}
export const skillArray=[]
export const addNewSkill = createAsyncThunk(
'skills/addNewSkill',
async (skillData,{rejectWithValue,dispatch}) =>{
const {skillName,skillRange} = skillData
try{
const skill = {
name: skillName,
range: skillRange,
};
const response = await fetch('/api/skills',{
method:'POST',
headers:{
'Content-name' : 'application/json',
},
body: JSON.stringify(skill)
});
skillArray.push(skill)
if(!response.ok){
throw new Error('Can\'t add skill. Server error')
}
const data = await response.json();
dispatch(setSkill(data))
}catch(error){
return rejectWithValue(error.message);
}
}
)
export const skillSlice = createSlice({
name: "skills",
initialState: {
skills:[],
status: null,
error: null
},
reducers: {
setSkill: (state, action) => {
// console.log("action", action.payload);
// state.name = action.payload?.name;
// state.range = action.payload?.range;
state.skills.push(action.payload);
// localStorage.setItem(state.name,action.payload.range)
},
},
extraReducers:{
[fetchSkills.pending]:(state,action)=>{
state.status = 'loading';
state.error = null;
},
[fetchSkills.fulfilled]:(state,action)=>{
state.status = 'resolved';
state.name = action.payload;
},
[fetchSkills.rejected]: setError,
}
});
const { setSkill } = skillSlice.actions;
export const selectSkill = (state) => state?.skill;
export default skillSlice.reducer;
根目录:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import { persistStore, persistReducer } from 'redux-persist'
import { toggleButtonReducer } from './reducers/toggleButtonReducer'
import storage from 'redux-persist/lib/storage'
import thunk from 'redux-thunk'
import educationReducer from '../features/education/educationSlice';
import skillReducer from '../features/skills/skillSlice'
const rootReducer = combineReducers({
visibilityState: toggleButtonReducer,
educationState: educationReducer,
skills : skillReducer
})
const persistConfig = {
key: 'root',
storage,
}
const persistedReducer = persistReducer(persistConfig, rootReducer)
export const store = createStore(persistedReducer, composeWithDevTools(applyMiddleware(thunk)))
export const persistor = persistStore(store)
我想我解决了这个问题,如果这是一个好的方法,我想知道,但是我没有推送任何东西就直接访问了商店。
const skillList = useSelector((state)=>state.skills.skills)
console.log("skills",skillList)
并这样映射:
<ul className="skills">
{skillList.map((skill, index) => <li
key={skill.skills.name}
style={{ width: `${skill.skills.level}%`}}
>
<p>{skill.skills.name}<span>{skill.skills.level}</span></p>
</li>
)}
</ul>
我得到了预期的结果,这很好,但它是否是一个好的方法,我不知道。