React条件渲染点击登出报this.state is not a function错误如何解决
React条件渲染报错修复方案
错误根因
- 核心语法错误:你在
handleLogoutClick方法中尝试调用this.state()修改状态,React类组件中this.state是存储状态值的普通对象,仅支持通过this.setState()方法触发状态更新,错误调用对象作为函数直接触发this.state is not a function报错。 - 潜在路径错误:入口文件中引入组件的路径拼写为
./compnents/Rendering,正确拼写应为./components/Rendering,否则会触发模块找不到的运行错误。
修复步骤
修改主组件文件中的handleLogoutClick方法,将this.state替换为this.setState即可:
// 修复后的登出事件处理函数 handleLogoutClick() { this.setState({ isLoggedIn: false, }); }
修复后完整主组件代码
import React, { Component } from "react"; export default class Rendering extends Component { constructor(props) { super(props); this.state = { isLoggedIn: false }; this.handleLoginClick = this.handleLoginClick.bind(this); this.handleLogoutClick = this.handleLogoutClick.bind(this); } // 登录事件处理函数 handleLoginClick() { this.setState({ isLoggedIn: true, }); } // 修复后的登出事件处理函数 handleLogoutClick() { this.setState({ isLoggedIn: false, }); } render() { const isLoggedIn = this.state.isLoggedIn; let button; if (isLoggedIn) { button = <LogoutButton onClick={this.handleLogoutClick} />; } else { button = <LoginButton onClick={this.handleLoginClick} />; } return <div className="App">{button}</div>; } } // 登录按钮组件 function LoginButton(props) { return <button onClick={props.onClick}>Login</button>; } // 登出按钮组件 function LogoutButton(props) { return <button onClick={props.onClick}>Logout</button>; }
入口文件修复(路径修正)
import React from "react"; import ReactDOM from "react-dom"; // 修复路径拼写错误 import Rendering from "./components/Rendering"; // 渲染 ReactDOM.render( <React.StrictMode> <Rendering /> </React.StrictMode>, document.getElementById("root") );
内容的提问来源于stack exchange,提问作者Siddharth Arya
相关产品推荐
相关产品推荐

