我正在使用React开发一个聊天应用程序,并不断在代码中指出以下错误:
TypeError:无法在字符串“ room1”上创建属性“ key”
我正在使用firebase作为数据库,并且有两个对象。我正在使用room1和room2,但在遍历两个对象时出现错误。
我已经待了好几天了,我收不了。这是我的代码:
import React, { Component } from 'react';
class RoomList extends Component {
constructor(props) {
super(props);
this.state = {
rooms: [],
newRoomName: ''
};
this.roomsRef = this.props.firebase.database().ref("rooms");
}
componentDidMount() {
this.roomsRef.on('child_added', snapshot => {
const room = snapshot.val();
room.key = snapshot.key;
this.setState({ rooms: this.state.rooms.concat( room ) })
});
}
createRoom(newRoomName) {
this.roomsRef.push({
name: newRoomName
});
this.setState({ newRoomName: '' });
}
handleChange(e) {
this.setState({ newRoomName: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
this.createRoom(this.state.newRoomName);
}
render() {
return (
<section className="room-list">
<h3>Rooms</h3>
{this.state.rooms.map( room =>
<li key={room.key} >
{room.name}
</li>
)}
<form id="create-room" onSubmit={ (e) => this.handleSubmit(e) }>
<input type="text" value={ this.state.newRoomName } onChange={ (e) => this.handleChange(e) }/>
<input type="submit" />
</form>
</section>
);
}
}
export default RoomList;
在room.key = snapshot.key
这是我的App.js文件
import React, { Component } from 'react';
import './App.css';
import * as firebase from 'firebase';
import RoomList from './components/RoomList';
// Initialize Firebase
var config = {
apiKey: "AIzaSyD4geqW7VZ7e7trfIASUQaWaJA9pmGDzUE",
authDomain: "bloc-chat-81cb7.firebaseapp.com",
databaseURL: "https://bloc-chat-81cb7.firebaseio.com",
projectId: "bloc-chat-81cb7",
storageBucket: "bloc-chat-81cb7.appspot.com",
messagingSenderId: "229890444186"
};
firebase.initializeApp(config);
class App extends Component {
constructor(props) {
super(props);
this.state = {
rooms: [],
newRoomName: ''
};
}
render() {
return (
<div className="App">
<h1 className="App-title">Bloc Chat</h1>
<main>
<RoomList firebase={firebase} />
</main>
</div>
);
}
}
export default App;