React - TypeError:无法读取未定义的属性(读取“参数”)?

noo23r

我正在尝试访问并 console.log id 参数,但不断收到错误消息,提示它们未定义。这是为什么?页面加载完美,我可以在 url 中看到用户 ID。但是当我转到 console.log 时,网页崩溃并显示无法读取未定义的属性(读取“参数”)

这是我尝试从参数中接收 id 的其他配置文件

     export default class OtherProfile extends Component {
  constructor(props) {
    super(props);
    console.log(this.props.match.params.id)

    this.state = {
      redirect: null,
      userDetails: [],
      activeItem: 'favourites'
    };
  }

  componentDidMount() {
    // const id = this.props.params.user._id;
    // console.log(id)
    // Axios.post('http://localhost:8080/api/user/getUserDetails')
    // .then(response => {
    //     if (response.data.success) {
    //         console.log('Users Details', response.data)
    //         setFavouriteList(response.data.films)
    //     } else {
    //         alert('Error')
    //     }
    // })
  }

  handleItemClick = (e, { name }) => this.setState({ activeItem: name })

  onClick = (e) => {
    this.props.history.push("/profile/edit");
  }


  renderSwitch(activeItem) {
    switch (activeItem) {
      case 'reviews':
        return <SentimentComponent />;
      case 'films':
        return <Films />;
      case 'portfolio':
        return <Portfolio />;
      case 'favourites':
        return <FavouriteContainer />;
      case 'futurefilms':
        return <FutureFilms />;
    }
  }


  render() {
    if (this.state.redirect) {
      return <Redirect to={this.state.redirect} />
    }
    const { activeItem } = this.state;

    return (
      <div className="container">
        {(this.state.userReady) ?
          <div>
            <br></br>
            <Avatar size={180} icon={<UserOutlined />}/>
            <p>
              <strong>Email:</strong>{" "}
              {/* {currentUser.email} */}
            </p>
            <strong>Username: </strong>
            {/* {currentUser.username} */}
            <p>
              <button onClick={this.onClick}> EDIT </button>
              {/* <strong>Phone Number: </strong>
              {currentUser.phoneNo} */}
            </p>
          </div> : null}
        <Menu>
          <Dropdown
            item text='Films'
            name='films'>
            <Dropdown.Menu>
            <Dropdown.Item
                name="favourites"
                active={activeItem === 'favourites'}
                onClick={this.handleItemClick}>
                Favourites
              </Dropdown.Item>
              <Dropdown.Item
                name="futurefilms"
                active={activeItem === 'futurefilms'}
                onClick={this.handleItemClick}>
                Future Films
              </Dropdown.Item>
            </Dropdown.Menu>
          </Dropdown>
          <Menu.Item
            name='reviews'
            active={activeItem === 'reviews'}
            onClick={this.handleItemClick}
          />
          <Menu.Item
            name='portfolio'
            active={activeItem === 'portfolio'}
            onClick={this.handleItemClick}
          />
          <Menu.Item
            name='campaign'
            active={activeItem === 'campaign'}
            onClick={this.handleItemClick}
          />
        </Menu>
        {this.renderSwitch(activeItem)}
      </div>
    );
  }
}

这是我发送我的身份证的地方

const UserListComponent = (props) => {
  const [loading, setLoading] = useState(true);
  const [userList, setUserList] = useState([]);
  const { username } = useParams();

  const history = useHistory();

  useEffect(() => {
    Axios.get(`http://localhost:8080/api/search?username=${username}`, {
      headers: authHeader(),
    })
      .then(({ data }) => {
        console.log(data.users);
        setUserList(data.users);
        setTimeout(() => setLoading(false), 500);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  }, []);

  return (
    <UserListContainer
      onClick={() => {
        //history.push(`/films/${props.movieList.movie.id}`)
      }}
    >
      {loading && <div>Loading...</div>}
      {!loading &&
        userList.map((user, i) => (
          <Link key={i} to={`/user/${user._id}`}>
            {user.username}
          </Link>
        ))}
      {!loading && userList.length === 0 && (
        <div>No users exist with the paramters!</div>
      )}
    </UserListContainer>
  );
};

export default UserListComponent;

这是我获得个人资料用户的地方

import React, { useEffect, useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import styled from 'styled-components';
import { useHistory } from 'react-router-dom'; // services
import authHeader from '../services/auth-header';
import Axios from 'axios';
import OtherProfile from './profile/OtherProfile'

const UserListContainer = styled.div`
  display: flex;
  flex-direction: column;

  padding: 30px;
  gap: 25px;
  justify-content: center;
  align-items: center;
`;

const MemberUser = (props) => {
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState(null);
  const { id } = useParams();
  const history = useHistory();

  useEffect(() => {
    Axios.get(`http://localhost:8080/api/user/?id=${id}`, {
      headers: authHeader(),
    })
      .then(({ data }) => {
        console.log(data);
        setUser(data);
        setTimeout(() => setLoading(false), 500);
      })
      .catch((err) => {
        console.log(err);
        setLoading(false);
      });
  }, []);

  return (
    <UserListContainer
      onClick={() => {
        //history.push(`/films/${props.movieList.movie.id}`)
      }}
    >
      {loading && <div>Loading...</div>}
      {!loading && user && (
      <OtherProfile/>
      )}
      {!loading && !user && <div>No users exist with that id!</div>}
    </UserListContainer>
  );
};

export default MemberUser;
尼古拉斯大厦
{!loading && user && (
  <OtherProfile/>
)}

您没有将任何道具传递给此元素,因此this.props.match将是未定义的。我不确切知道您希望匹配逻辑做什么,但可能是这样的:

const MemberUser = (props) => {
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState(null);
  const { id } = useParams();
  const history = useHistory();
  const match = useRouteMatch("/user/:id"); // <---- added

  // ...

  {!loading && user && (
    <OtherProfile match={match} />
  )}

  // ...
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

React TypeError:无法读取未定义的属性(读取“状态”)

React TypeError:无法读取未定义的属性“结果”

MobX React TypeError:无法读取未定义的属性

React TypeError:无法读取未定义的属性“0”

TypeError:无法读取未定义的React Express的属性'prototype'

React-TypeError:无法读取未定义的属性“ includes”

TypeError:无法读取未定义的React Hooks的属性“ map”

React教程:TypeError:无法读取未定义的属性“ props”

TypeError:无法读取未定义React的属性'value'

React Jest:TypeError:无法读取未定义的属性“ map”

React - TypeError 无法读取未定义的属性“地图”

React + Fetch + Json。TypeError:无法读取未定义的属性

React Native + Fetch => TypeError:无法读取未定义的属性“then”

React TypeError:无法读取未定义的属性“绑定”

TypeError:无法读取未定义的属性'then'-React Hooks

× react TypeError:无法读取未定义的属性“then”

REACT TypeError:无法读取未定义的属性“值”

TypeError:无法在react中读取未定义的属性'reduce'

TypeError:无法读取未定义的属性“状态”。更新了React

Typescript,React:TypeError:无法读取未定义的属性“ push”

TypeError:无法读取未定义的React Native的属性'map'

React - TypeError:无法读取未定义的属性“renderSidebaritem”

React TypeError:无法读取未定义问题的属性“categoryName”

React JSX 返回 TypeError:无法读取未定义的属性

React js TypeError:无法读取未定义的属性“params”

React Redux TypeError:无法读取未定义的属性“标题”

React-TypeError:无法读取未定义的属性“img”

React无法读取未定义的属性

Axios在React中未定义,错误:Uncaught TypeError:无法读取未定义的属性“ post”