我正在构建一个组件,该组件在每次新用户加入我的服务器时都会更新。我的componentDidUpdate发出了一个我从redux中拉出的新用户,然后我在构造函数中接收到响应并使用它设置状态。当我对接收到的数据进行console.log记录时,一切都是我期望的样子,但是我无法映射状态并为每个元素呈现一个组件。
import React, { Component } from "react"
import "./SearchSideBar.css"
import socketIOClient from 'socket.io-client';
import Contact from "../Contact/Contact";
import { connect } from "react-redux"
import { updateUsersConnected } from "../../Redux/reducer"
const socket = socketIOClient("http://localhost:4000/");
export class SearchSideBar extends Component{
constructor(){
super()
this.state = {
toggleSearch:false,
usersConnected:[]
}
socket.on("UserEnter", data =>{
console.log(data)
this.setState({
usersConnected:data
})
// this.props.updateUsersConnected(data)
console.log("Users in this room : ", this.state.usersConnected)
})
}
handleButtonPress = () =>{
this.setState({
toggleSearch:!this.state.toggleSearch
})
}
componentDidUpdate = (prevProps) =>{
if(this.props.user.email != prevProps.user.email){
socket.emit("NewUser", this.props.user)
}
}
render(){
console.log(this.state)
return(
<div className = "search-parent">
<div className = "container-header">
<h3 className = "title">Who's Online?</h3>
<button onClick={() =>{this.handleButtonPress()}}><img className = "searchIcon" src="https://img.icons8.com/ios-glyphs/30/000000/search.png"></img></button>
</div>
<div className = {this.state.toggleSearch? "show":"hidden"}>
<input className = "searchbar" placeholder = "Search for a name or department"></input>
</div>
{
this.state.usersConnected.length? this.state.usersConnected.map(user =>{
return(
<div>
<Contact/>
</div>
)
})
:
console.log("Doesn't work")
}
</div>
)
}
}
const mapStateToProps = (state) =>{
return{
user:state.user
}
}
export default connect(mapStateToProps,{updateUsersConnected}(SearchSideBar)