我正在try 访问和控制台.记录id参数,但不断收到一个错误,表示它们未定义.为什么?页面加载完美,我可以在url中看到用户id.但当我go 慰问台的时候.记录它网页崩溃,它说无法读取未定义的属性(读取'params')

这是另一个配置文件,我try 从param接收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/>
)}

你没有向这个元素传递任何props ,所以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} />
  )}

  // ...
}

Javascript相关问答推荐

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

防止用户在selectizeInput中取消 Select 选项

React Code不在装载上渲染数据,但在渲染上工作

将自定义排序应用于角形数字数组

未捕获错误:[]:getActivePinia()被调用,但没有活动Pinia.🍍""在调用app.use(pinia)之前,您是否try 使用store ?""

如何从Intl.DateTimeFormat中仅获取时区名称?

如果Arrow函数返回函数,而不是为useEffect返回NULL,则会出现错误

如何在ASP.NET中使用Google Charts API JavaScript将条形图标签显示为绝对值而不是负值

将内容大小设置为剩余可用空间,但如果需要,可在div上显示滚动条

第二次更新文本输入字段后,Reaction崩溃

自定义图表工具提示以仅显示Y值

在验证和提交表单后使用useNavigate()进行react 重定向,使用带有加载器和操作的路由

如何在一个对象Java脚本中获取不同键的重复值?

FileReader()不能处理Firefox和GiB文件

为列表中的项目设置动画

顶点图使用组标签更新列之间的条宽

将延迟加载的模块转换为Eager 加载的模块

使用props 将VUE 3组件导入JS文件

如何将值从后端传递到前端

将数据添加到数据库时不输出