gpt4 book ai didi

reactjs - 在 react 中的功能组件内编写功能

转载 作者:行者123 更新时间:2023-12-05 01:41:29 25 4
gpt4 key购买 nike

在我的应用程序中,我在功能组件下编写了一个功能,但它不起作用。它说,函数未定义 no-undef。但是我在我以前的项目中写过同样的代码。我在这里做错了什么?如果我将其转换为类组件,则效果很好。是否可以编写这样的代码?还是必须将其更改为类组件?

import React from 'react';
import { Link } from 'react-router-dom';

import PropTypes from 'prop-types';
import {bindActionCreators} from 'redux';
import { connect } from 'react-redux';
import { logoutUser, clearCurrentProfile } from '../../actions';

const Navbar = props => {

const { isAuthenticated, user } = props.auth;

onLogoutClick = e => {
e.preventDefault();

props.clearCurrentProfile();
props.logoutUser();
}

const authLinks = (
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link className="nav-link" to="/feed">
Post Feed
</Link>
</li>

<li className="nav-item">
<Link className="nav-link" to="/dashboard">
Dashboard
</Link>
</li>

<li className="nav-item">
<img
className="rounded-circle"
style={{ width: '25px' }}
src={user.avatar}
alt={user.name}
/>
<button
type="button"
className="link-button nav-link"
onClick={() => this.onLogoutClick().bind(this)}>
Logout
</button>
</li>
</ul>
);

const guestLinks = (
<ul className="navbar-nav ml-auto">
<li className="nav-item">
<Link className="nav-link" to="/register">
Sign Up
</Link>
</li>

<li className="nav-item">
<Link className="nav-link" to="/login">
Login
</Link>
</li>
</ul>
);

return (
<nav className="navbar navbar-expand-sm navbar-dark bg-dark mb-4">
<div className="container">
<Link className="navbar-brand" to="/">
DevConnector
</Link>

<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#mobile-nav">
<span className="navbar-toggler-icon"></span>
</button>

<div className="collapse navbar-collapse" id="mobile-nav">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<Link className="nav-link" to="/profiles">
Developers
</Link>
</li>
</ul>

{isAuthenticated ? authLinks : guestLinks}
</div>
</div>
</nav>
);
};

Navbar.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
}

const mapStateToProps = state => ({
auth: state.auth
});

const mapDispatchToProps = dispatch => ({
logoutUser: bindActionCreators(logoutUser, dispatch),
clearCurrentProfile: bindActionCreators(clearCurrentProfile, dispatch)
});

export default connect(mapStateToProps, mapDispatchToProps)(Navbar);

最佳答案

const onLogoutClick定义,调用时不需要this关键字。

bind 当您已经使用箭头函数进行词法绑定(bind)时也是不必要的。

const Navbar = props => {
// ...

const onLogoutClick = e => { // use consts or let
e.preventDefault()

props.clearCurrentProfile()
props.logoutUser()
}

const authLinks = (
// ...
<button
type="button"
className="link-button nav-link"
onClick={onLogoutClick} // no need 'this' keyword
>

...rest of your stuffs

关于reactjs - 在 react 中的功能组件内编写功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54320062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com