【问题标题】:Why do I have problem rendering this conditional JSX?为什么我在渲染这个条件 JSX 时遇到问题?
【发布时间】:2021-10-09 09:16:53
【问题描述】:

我在 React 中有条件地显示 JSX 时遇到问题。

我想在用户未登录时显示登录表单,并在用户登录时显示 h1。 但是,当我登录时,登录表单仍然存在并且 h1 没有出现。为什么会这样?

■App.js

import React from 'react';
import Login from './Views/Login/Login';
import { useSelector } from 'react-redux';

function App() {
  const isLoggedIn = useSelector((state) => {
    state.auth.loggedIn;
  });

  return (
  <div>
    <h1>TEST</h1>
    {isLoggedIn && <h1>LoggedIn</h1>}
    {!isLoggedIn && <Login />}
  </div>
  );
}
export default App;

■index.js(存储)

import { configureStore } from '@reduxjs/toolkit';
import authReducer from './auth-slice';

const store = configureStore({
  reducer: { auth: authReducer},
});


export default store;

■auth-slice.js

import { createSlice } from '@reduxjs/toolkit';

const authSlice = createSlice({
  name: 'auth',
  initialState: { admin: false, loggedIn: false },
  reducers: {
    login(state, action) {
    const { name, password } = action.payload;
    state.loggedIn = true;
    state.admin = true;
    console.log(name, password, state.loggedIn);
    },
  },
});

export default authSlice.reducer;
export const authActions = authSlice.actions;

【问题讨论】:

    标签: reactjs redux react-redux jsx redux-toolkit


    【解决方案1】:

    使用arrow functions时,如果使用花括号,则必须编写return语句

    否则,函数会隐式返回undefined。 因此,在您的情况下,isLoggedIn 始终未定义。 falsy value 表示登录表单将始终显示。

    const isLoggedIn = useSelector((state) => 
        state.auth.loggedIn;
      );
    
    

    【讨论】:

    • 这完全有效!谢谢!我不知道如果没有 return 语句,返回的值将是未定义的……今天学到了一些新东西!
    • 很高兴。查看我添加的箭头功能的 MDN 链接。请考虑投票/接受答案。
    猜你喜欢
    • 2023-03-28
    • 2020-10-12
    • 2010-10-21
    • 1970-01-01
    • 2020-03-06
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    相关资源
    最近更新 更多