【问题标题】:my users details is not is not rendering users list when i type in search我的用户详细信息不是在我输入搜索时不呈现用户列表
【发布时间】:2021-05-23 03:34:23
【问题描述】:

还有一个错误 TypeError: Cannot destructure property 'handleShow' of 'object null' 因为它是空的。 我控制台日志时的输出是 公关 SearchModal.js:35 {用户名:“pr”} SearchModal.js:38 [{…}]0:{id:“602df77cea2b563d7ceda4ac”,用户名:“pratik”,电子邮件:“pratik@gmail.com”}长度:1__proto_:数组(0 ) 当我输入 p 它给 searc:'' 时它也没有搜索,当我添加 prat 然后搜索:'pra' only 此外,它不会呈现用户名,只需检查 userdetails.map 它是控制台记录详细信息,但不会在页面上呈现

import React, { Component } from 'react';
import { SearchUser } from '../services/SearchService';
import {Modal} from 'react-bootstrap';

class SearchModal extends Component {
  constructor(props){
    super(props);
    this.state = {
        show: false,
        search: '',
        userdetails:[]
    }

    this.handleShow = this.handleShow.bind(this);
    this.handleClose = this.handleClose.bind(this);
    this.onTextboxChangeSearch = this.onTextboxChangeSearch.bind(this);
}
handleShow() {
    this.setState({ show: true })
}
handleClose(){
    this.setState({ show: false })
}

async onTextboxChangeSearch(event) {

  this.setState({
      search: event.target.value
  });
  let {search,userdetails} = this.state;
  console.log(search)


  const data = {username:search};
  console.log(data)
  let SearchStatus = await SearchUser(data);
  userdetails=SearchStatus.user
  console.log(userdetails);
}

render() {
    let {search,userdetails}= this.state;

    return (
       <div>
          <Modal show={this.state.show} onHide={this.handleClose}>
             <Modal.Header closeButton>
               <Modal.Title>
                 <input 
                  type="text" 
                  placeholder="Search.."
                  value={search}
                  onChange={this.onTextboxChangeSearch}
                 ></input>
               </Modal.Title>
             </Modal.Header>
             <Modal.Body>
               <h3>Users</h3>
               <div>
               <ul>
                {userdetails.map(element => {
                  <li>{element.username}</li>
                })}
              </ul>
               </div>
             </Modal.Body>
          </Modal>
        </div>
    )
  }
}
export default SearchModal;

仪表板

import React, { Component } from 'react';
import { Link,Redirect } from 'react-router-dom';
import UserService from "../services/userservice";
import SearchModal from './SearchModal'

export default class Dashboard extends Component{

    constructor(props) {
        super(props);
    
        this.state = {
            currentUser: UserService.getCurrentUser(),
            isLoading:false,
        };

        this.logOut = this.logOut.bind(this);
        this.onClick = this.onClick.bind(this);

    }

    logOut() {
        UserService.logout()
    }

    SearchModalRef = ({handleShow}) => {
        this.showModal = handleShow;
    }
    
    onClick = () => {
        this.showModal();
    }
     

    render(){
        const { currentUser ,isLoading } = this.state;
        console.log(currentUser)

        if (isLoading) {
            return (<div><p>Loading...</p></div>);
        }

        if(!currentUser){
            return(
                <div>
                    <Redirect  to='/login' />
                </div>
            )
        }
        else{
            return(
                <div>
                    <header>
                        <h1>Dashboard</h1>
                        {' '}
                        <div>
                            <Link to={`/dashboard/profile/:${currentUser.user._id}`}>Profile</Link>
                        </div>
                        {' '}
                        <div>
                            <Link to="/login" onClick={this.logOut}>LogOut</Link>
                        </div>
                        {' '}
                        
                        <SearchModal  ref={this.SearchModalRef} ></SearchModal>
                        <button type="button" onClick={this.onClick}>
                        Search
                        </button>
                    </header>
                    <div>

                    </div>
                </div>
            );
        }
    }
}

【问题讨论】:

  • 我看不出你在哪里试图从任何东西中解构handleShow,更不用说它在哪里被使用或引用了。关于您的另一个问题,反应状态更新是异步的,因此您不能将状态更新排入队列并期望稍后在同一函数中使用排入队列的状态值。换句话说,这就是为什么search 值在onTextboxChangeSearch 后面是一个渲染周期。
  • 所以我能做什么
  • 使用event.target.value而不是在onTextboxChangeSearch的正文中搜索,或者保留状态更新并将搜索逻辑重构为它自己的函数,该函数在componentDidUpdate生命周期方法中调用search 状态值。
  • sry 我没明白你要我做什么你能把它写出来

标签: reactjs compiler-errors console warnings mern


【解决方案1】:

问题

当我输入 p 它给 searc:'' 并且当我添加时它没有搜索 prat 然后搜索:'pra' only

React 状态更新是异步的,并且在渲染周期之间进行批处理。这意味着当您将状态更新排入队列时,它将在下一个渲染周期之前不可用。在同一函数中对状态的任何进一步引用都将是当前渲染周期中的状态值。

async onTextboxChangeSearch(event) {
  this.setState({
    search: event.target.value // <-- next state
  });
  let {search,userdetails} = this.state; // <-- still current state!
  console.log(search)

  const data = {username:search};
  console.log(data)
  let SearchStatus = await SearchUser(data);
  userdetails=SearchStatus.user
  console.log(userdetails);
}

解决方案

我建议将搜索逻辑分解到它自己的函数中,以便在状态更新时由componentDidUpdate 生命周期方法调用。

onTextboxChangeSearch(event) {
  const { value } = event.target;
  this.setState({
    search: value // <-- (1) update state
  });
}


searchForUser = async () => { // <-- (3) refactored search function
  const { search, userdetails } = this.state;
  const data = { username: search };

  const { user } = await SearchUser(data);
  this.setState(prevState => ({
    userdetails: [...prevState.userdetails, user], // append user
  }));
}

componentDidUpdate(prevProps, prevState) {
  if (prevState.search !== this.state.search) {
    this.searchForUser(); // <-- (2) search state updated, do search for user
  }
}

【讨论】:

  • 它给出了这个错误第 43:5 行:'searchForUser' is not defined no-undef
  • @PratikZinjurde 它是一个箭头函数,您不需要在构造函数中进行任何绑定。实际上,我只是忘记将其称为this. searchForUser,所以是我的错字。我至少有一年没有使用基于类的组件了,但 IDE 会很容易做到这一点。答案已更新。抱歉给您带来麻烦/困惑。
  • 正是我在想我也删除了绑定谢谢@DrewReese 赞赏
  • 这在控制台日志数据中现在不能正常工作,用户详细信息是 {username: "a"} SearchModal.js:41 [] SearchModal.js:37 {username: "ab"} SearchModal.js :41 (2) [{…}, {…}] 0: {_id: "602d50fb11d7500428c270b8", 用户名: "abc", 电子邮件: "abc@gmail.com"} 1: {_id: "602df77cea2b563d7ceda4ac", 用户名: “pratik”,电子邮件:“pratik@gmail.com”} 长度:2 proto:Array(0)
  • 还有为什么不渲染列表
      {userdetails.map(element => {
    • {element.username}
    • })}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-18
  • 2011-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-08
  • 1970-01-01
相关资源
最近更新 更多