下面的代码可以通过在弹出框中显示用户信息来正常工作。
现在,我想向每个用户发送消息到nodejs服务器。该消息已发布,因为我可以在nodejs服务器端看到它
安慰。
在reactjs控制台中,按照下面的代码
const addMessage = data => {
console.log(data);
this.setState({messages: [...this.state.messages, data]});
};
正在按以下方式在控制台中看到发送的消息
{author: "Nancy ", message: "first message"}
这是我的问题:
1.)尽管我已将其设置为this.props.messages。,该消息仍未显示在render方法中。
2.)当我在输入表单上键入内容时,按照以下说明在控制台中看到错误警告
警告:组件正在更改要控制的文本类型的不受控制的输入。
输入元素不应从不受控制切换为受控制(反之亦然)。
确定在组件的使用寿命期间使用受控或不受控制的输入元素。
在输入中(由OpenedUser创建)
以下是如何从Node.js服务器发布和检索它
componentDidMount(){
this.socket = io('http://localhost:8080');
this.socket.on('response message', function(data){
addMessage(data);
});
const addMessage = data => {
console.log(data);
this.setState({messages: [...this.state.messages, data]});
};
} // close component didmount
sendMessage = ev => {
ev.preventDefault();
this.socket.emit('chatMessage', {
author: this.state.username,
message: this.state.message
})
this.setState({message: ''});
}
这是到目前为止的完整工作代码
//npm install --save socket.io
//npm install --save socket.io-client
import React, { Component, Fragment } from "react";
import { render } from "react-dom";
import { Link } from 'react-router-dom';
import axios from 'axios';
import io from "socket.io-client";
class User extends React.Component {
open = () => this.props.open(this.props.data.id, this.props.data.name);
render() {
return (
<React.Fragment>
<div key={this.props.data.id}>
<button
onClick={() => this.open(this.props.data.id, this.props.data.name)}
>
{this.props.data.name}
</button>
</div>
</React.Fragment>
);
}
}
class OpenedUser extends React.Component {
constructor(props) {
super(props);
this.state = {
hidden: false
};
}
componentDidMount(){
this.socket = io('http://localhost:8080');
this.socket.on('response message', function(data){
addMessage(data);
});
const addMessage = data => {
console.log(data);
this.setState({messages: [...this.state.messages, data]});
};
} // close component didmount
sendMessage = ev => {
ev.preventDefault();
this.socket.emit('chatMessage', {
author: this.state.username,
message: this.state.message
})
this.setState({message: ''});
}
toggleHidden = () => this.setState(prevState => ({ hidden: !prevState.hidden }));
close = () => this.props.close(this.props.data.id);
render() {
return (
<div key={this.props.data.id} style={{ display: "inline-block" }}>
<div className="msg_head">
<button onClick={this.close}>close</button>
<div>user {this.props.data.id}</div>
<div>name {this.props.data.name}</div>
{this.state.hidden ? null : (
<div className="msg_wrap">
<div className="msg_body">Message will appear here</div>
<b> {" "} Display Chat Message below...{" "}</b>
<div>
{this.props.messages.map(message => {
return (
<div>{message.author}: {message.message}</div>
)
})}
</div>
<div>
<input type="text" placeholder="Username" value={this.state.username} onChange={ev => this.setState({username: ev.target.value})}/>
<br/>
<input type="text" placeholder="Message" value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
<br/>
<button onClick={this.sendMessage} className="btn btn-primary">Send message</button>
</div>
</div>
)}
</div>
</div>
);
}
}
class App extends React.Component {
constructor() {
super();
this.state = {
loading_image: false,
shown: true,
activeIds: [],
username: '',
message: '',
messages: [],
data: [
{ id: 1, name: "user 1" },
{ id: 2, name: "user 2" },
{ id: 3, name: "user 3" },
{ id: 4, name: "user 4" },
{ id: 5, name: "user 5" }
]
};
}
toggle() {
this.setState({
shown: !this.state.shown
});
}
open = (id, name) => {
alert(id);
alert(name);
//start axios api call
const user_data = {
uid: "id",
uname: "name"
};
this.setState(prevState => ({
activeIds: prevState.activeIds.find(user => user === id)
? prevState.activeIds
: [...prevState.activeIds, id]
}));
};
close = id => {
this.setState(prevState => ({
activeIds: prevState.activeIds.filter(user => user !== id)
}));
};
renderUser = id => {
const user = this.state.data.find(user => user.id === id);
if (!user) {
return null;
}
return (
<OpenedUser
chatData={this.state.chatData} messages={this.state.messages}
key={user.id}
data={user}
close={this.close}
/>
);
};
renderActiveUser = () => {
return (
<div style={{ position: "fixed", bottom: 0, right: 0 }}>
{this.state.activeIds.map(id => this.renderUser(id))}
</div>
);
};
render() {
return (
<div>
{this.state.data.map(person => (
<User key={person.id} data={person} open={this.open} />
))}
{this.state.activeIds.length !== 0 && this.renderActiveUser()}
</div>
);
}
}
最佳答案
在OpenedUser.sendMessage
中,您具有以下代码分别将input
值与this.state.username/message
关联。
// Reformatted to remove scrollbars
<input type="text" placeholder="Username"
value={this.state.username}
onChange={ev => this.setState({username: ev.target.value})}/>
<br />
<input type="text" placeholder="Message"
value={this.state.message}
onChange={ev => this.setState({message: ev.target.value})}/>
最初,您的
this.state.username/message
是未定义的,因此React将这两个组件视为uncontrolled
。请参考以下文档
Forms -> Controlled-官方React文档
Uncontrolled Components-官方React文档
一旦为
onChange
中的这些状态设置了值,React现在就会认为您正在更改controlled
组件值,如错误消息所示。警告:组件正在更改要控制的文本类型的不受控制的输入。
因此,您需要做的是在
OpenedUser
中用其余现有状态hidden
声明这两个状态值。class OpenedUser extends React.Component {
constructor(props) {
super(props);
this.state = {
hidden: false,
// empty/props or other sensible default value
message: "",
// empty/props or other sensible default value
username: ""
};
}
// omitted for brevity...
}
抱歉,我无法测试上面的代码。