我必须创建一个React + Redux应用程序,它基本上是一个电影数据库管理应用程序。目前,只能查看电影详细信息、删除电影和登录(才能删除该电影)。我已经设置了一个初始状态,里面有3部电影,用户的一些基本数据是可用的。user对象包含以下字段: isLoggedIn、昵称和密码(我将最后两个字段保存为状态,因为我不使用任何API从服务器或任何类似的地方获取数据)。登录时,状态对象user应将其isLoggedIn字段更改为true (默认值为false)并显示delete按钮。
问题是:如何将isLoggedIn从true更改为false,同时保持用户对象的其余部分和存储的其余部分完好无损?
这是我到目前为止尝试的(我还没有完成开关,我知道我必须设置一个默认值):
import { createStore } from 'redux'
const initialState = {
movies: [
{ id: '1', movie_title: 'John Wick Chapter 2', year: '2017', main_actor: 'Keanu Reeves', summary: `The hitman that's been retired then back then retired strikes again, this time against the Mafia.`, cover: '%PUBLIC_URL%/john_wick_2.png' },
{ id: '2', movie_title: 'Star Wars Revenge of the Sith', year: '2005', main_actor: 'Ewan McGregor', summary: `Anakin betrays Space Jesus so General Kenobi is forced to Mustafar Anakin.`, cover: '%PUBLIC_URL%/sw_rots.png' },
{ id: '3', movie_title: 'Star Wars The Clone Wars', year: '2008 - 2020', main_actor: 'Ewan McGregor, Hayden Christensen', summary: `Yoda has finally overdosed on Ketamine, Mace Window hasn't been defenestrated yet and The Negotiator has proven himself incapable of falling to the Dark Side`, cover: '%PUBLIC_URL%/sw_tcw.png' }
],
user: {
isLoggedIn: 'false',
nickname: 'obi_wan',
password: '12345'
}
}
const rootReducer = (state = initState, action) => {
switch(action.type){
case(action.type === 'DELETE_MOVIE'):
let newMovieList = state.movies.filter(movie => {
return action.id !== movie.id
})
return {
...state,
movies: newMovieList
}
case(action.type === 'LOG_IN'):
let newUser = ...user, action.isLoggedIn
return (
...state,
user: Object.assign(user, action.isLoggedIn);
)
}
return state;
}下面是movieActions和userActions:
export const loginAction = (isLoggedIn) => {
return {
type: 'LOG_IN',
isLoggedIn: 'true'
}
}
export const deleteMovieAction = (id) => {
return {
type: 'DELETE_MOVIE',
id
}
}这是GitHub上的项目:https://github.com/liviu-ganea/movie-database
发布于 2021-01-14 21:00:46
const rootReducer = (state = initState, action) => {
switch(action.type){
case(action.type === 'DELETE_MOVIE'):
let newMovieList = state.movies.filter(movie => {
return action.id !== movie.id
})
return {
...state,
movies: newMovieList
}
case(action.type === 'LOG_IN'):
return (
...state,
user: {
...state.user,
isLoggedIn: action.isLoggedIn,
}
)
}
return state;
}就像这样。
发布于 2021-01-15 09:32:26
只需使用扩展运算符,请记住,action应该只有一个类型和一个有效负载,因此将参数放在有效负载对象中会更好。
return ({
...state,
user: {
...state.user,
isLoggedIn: action.payload.isLoggedIn
})https://stackoverflow.com/questions/65719288
复制相似问题