[英]React Error: Objects are not valid as a React child,If you meant to render a collection of children, use an array instead
i am new to the react when i have done a crud application using React and flux i got this error my codes are below, 当我使用React和Flux完成一个Crud应用程序时,我是React的新手,我的错误在下面,
import React, { Component } from "react";
import $ from "jquery";
import UserStore from "../../stores/UserStore";
import * as UserActions from "../../actions/UserActions";
import AddUser from "./AddUser";
$.DataTable = require("datatables.net");
class UserList extends Component {
constructor() {
super();
this.getUsers = this.getUsers.bind(this);
this.state = {
users: UserStore.getAll()
};
this.loadUsers();
}
componentDidMount() {
$(document).ready(function() {
$("#example").DataTable({
ordering: true
});
});
}
componentWillMount() {
UserStore.on("change", this.getUsers);
}
componentWillUnmount() {
UserStore.removeListener("change", this.getUsers);
}
getUsers() {
console.log(" get users called");
this.setState({
users: UserStore.getAll()
});
}
loadUsers() {
UserActions.getUsersList();
}
render() {
const userlistitem = this.state.users.map((user, index) => (
<tr key={index}>
<th scope="row">{index}</th>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
<td>{user.dob}</td>
<td>{user.address}</td>
<td>{user.mobile}</td>
<td>{user.branch}</td>
</tr>
));
return (
<div
style={{
marginTop: 80,
marginLeft: 150,
marginRight: 150
}}
>
<div className="card text-white bg-info mb-3">
<div className="card-body">
<div className="d-flex justify-content-between">
<h5>User List</h5>
<div>
<button
style={{
marginTop: 10
}}
type="button"
className="btn btn-light "
data-toggle="modal"
data-target="#exampleModalCenter"
>
Add New User
</button>
</div>
</div>
</div>
</div>
<table id="example" className="table table-bordered table-striped ">
<thead className="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">User Name</th>
<th scope="col">Email</th>
<th scope="col">DOB</th>
<th scope="col">Address</th>
<th scope="col">Mobile</th>
<th scope="col">Branch</th>
</tr>
</thead>
<tbody>{userlistitem}</tbody>
</table>
<AddUser />
</div>
);
}
}
export default UserList;
import React, { Component } from "react";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import "../../css/datepicker.css";
import * as UserActions from "../../actions/UserActions";
class AddUser extends Component {
constructor(props) {
super(props);
this.state = {
branch: "",
name: "",
username: "",
mobile: "",
email: "",
address: "",
dob: new Date()
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handledatepickerchange = this.handledatepickerchange.bind(this);
}
handleInputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({ [name]: value });
}
handledatepickerchange(event) {
this.setState({ dob: event });
}
createUser = () => {
console.log("this is:", this);
const user = {
branch: this.state.branch,
name: this.state.name,
username: this.state.username,
mobile: this.state.mobile,
email: this.state.email,
address: this.state.address,
dob: this.state.dob
};
UserActions.createNewUser(user);
this.setState({
branch: "",
name: "",
username: "",
mobile: "",
email: "",
address: "",
dob: new Date()
});
};
render() {
return (
<div
className="modal fade"
id="exampleModalCenter"
tabIndex="-1"
role="dialog"
aria-labelledby="exampleModalCenterTitle"
aria-hidden="true"
>
<div className="modal-dialog modal-dialog-centered" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="exampleModalCenterTitle">
Add New User
</h5>
<button
type="button"
className="close"
data-dismiss="modal"
aria-label="Close"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-body">
<div className="input-group mb-3">
<input
name="name"
type="text"
className="form-control"
placeholder="Name"
aria-label="Name"
aria-describedby="button-addon2"
value={this.state.name}
onChange={this.handleInputChange}
/>
</div>
<div className="input-group mb-3">
<input
name="username"
type="text"
className="form-control"
placeholder="User Name"
aria-label="User Name"
aria-describedby="button-addon2"
value={this.state.username}
onChange={this.handleInputChange}
/>
</div>
<div className="input-group mb-3">
<input
name="email"
type="email"
className="form-control"
placeholder="Email"
aria-label="Email"
aria-describedby="button-addon2"
value={this.state.email}
onChange={this.handleInputChange}
/>
</div>
<div className="input-group mb-3">
<input
name="address"
type="text"
className="form-control"
placeholder="Address"
aria-label="Address"
aria-describedby="button-addon2"
value={this.state.address}
onChange={this.handleInputChange}
/>
</div>
<div className="input-group mb-3">
<input
name="branch"
type="text"
className="form-control"
placeholder="Branch"
aria-label="Branch"
aria-describedby="button-addon2"
value={this.state.branch}
onChange={this.handleInputChange}
/>
</div>
<div className="input-group mb-3">
<DatePicker
name="dob"
type="text"
className="form-control"
placeholder="DOB"
aria-label="DOB"
aria-describedby="button-addon2"
selected={this.state.dob}
onChange={this.handledatepickerchange}
/>
<p
style={{
marginTop: "5px",
fontWeight: "200",
marginLeft: "10px"
}}
>
Date of Birth(dd/mm/yyyy)
</p>
</div>
<div className="input-group mb-3">
<input
name="mobile"
type="number"
className="form-control"
placeholder="Mobile No."
aria-label="Mobile No."
aria-describedby="button-addon2"
value={this.state.mobile}
onChange={this.handleInputChange}
/>
</div>
</div>
<div className="modal-footer">
<br />
<br />
<button
type="button"
className="btn btn-secondary"
data-dismiss="modal"
>
Close
</button>
<button
type="button"
className="btn btn-primary"
data-dismiss="modal"
onClick={this.createUser}
>
Save
</button>
</div>
</div>
</div>
</div>
);
}
}
export default AddUser;
import dispatcher from "../dispatcher/dispatcher";
import { BASE_URL } from "../utils/AppConstants";
export function getUsersList() {
console.log("getting the data! ");
fetch(BASE_URL + "/users")
.then(res => res.json())
.then(
result => {
console.log("res " + result);
dispatcher.dispatch({ type: "RECEIVE_USERS", users: result });
},
// Note: it's important to handle errors here instead of a catch() block so that
// we don't swallow exceptions from actual bugs in components.
error => {
// here manage error and close loading;
console.log("getting error " + error);
}
);
}
export function createNewUser(user) {
console.log("post the data!");
fetch(BASE_URL + "/saveuser", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(user)
})
.then(res => res.json())
.then(
result => {
dispatcher.dispatch({ type: "CREATE_USER", newUser: user });
},
// Note: it's important to handle errors here instead of a catch() block so that
// we don't swallow exceptions from actual bugs in components.
error => {
// here manage error and close loading;
console.log("getting error " + error);
}
);
}
import { EventEmitter } from "events";
import dispatcher from "../dispatcher/dispatcher";
class UserStore extends EventEmitter {
constructor() {
super();
dispatcher.register(this.handleActions.bind(this));
this.users = [
{
branch: "19",
name: "Javcbvcsim11",
username: "zxcv",
mobile: "5645654",
email: "demo@gmail.com111",
address: "Demo vcbvcbAddress1",
dob: "2020-11-06T00:00:00.000+0000"
}
];
}
createUser(newUser) {
this.users.push(newUser);
console.log("new users lenght " + this.users.lenght);
this.emit("change");
}
getAll() {
return this.users;
}
handleActions(action) {
switch (action.type) {
case "RECEIVE_USERS": {
this.users = action.users;
this.emit("change");
break;
}
case "CREATE_USER": {
this.createUser(action.newUser);
break;
}
}
}
}
export default new UserStore();
I don't know what is the problem happened here.When checked in stack over flow i got that it's the problem of iterating the data. 我不知道这里发生了什么问题。当在堆栈中检查流时,我得到了迭代数据的问题。 But i already did that. 但是我已经做到了。 even though the error remain still.If any one can help it will be much appreciable. 即使错误仍然存在,如果有任何人可以提供帮助,它将非常可观。 The error thrown in setState method. setState方法中引发的错误。 i am here using flux as the architecture.The problem occures when i try to add a new user to my data.Actualyy when i add it inserting to db without any problem. 我在这里使用flux作为体系结构。当我尝试向数据中添加新用户时出现问题。 the problem is when i click save button in my AddUser component it saves in to my db but after it need to show again as a table list but the error throws. 问题是,当我单击AddUser组件中的“保存”按钮时,它保存到我的数据库中,但是在它需要再次显示为表列表之后却抛出错误。
One problem which I can see is that you're using user.dob
directly inside a JSX element ( <td>{user.dob}</td>
). 我看到的一个问题是,您直接在JSX元素( <td>{user.dob}</td>
)内部使用user.dob
。 dob
is either new Date()
or the direct output of react-datepicker
's onChange
event, both of which are objects. dob
是new Date()
或react-datepicker
的onChange
事件的直接输出,两者都是对象。
Here's a dummy component which tried to render {new Date()}
. 这是一个试图渲染{new Date()}
的虚拟组件。
const App = ({ text }) => <p>{text}</p>; // Passing Date object. ReactDOM.render(<App text={new Date()} />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>
This results in an error like this for me: 这对我来说是这样的错误:
Objects are not valid as a React child (found: Mon Jan 21 2019 12:37:56 GMT+0530 (India Standard Time)). 对象作为React子对象无效(发现:2019年1月21日星期一12:37:56 GMT + 0530(印度标准时间))。
Which means you're passing an object, not a string as a child to a JSX element. 这意味着您要将一个对象而不是字符串作为子代传递给JSX元素。
Notice how this works: 注意这是如何工作的:
const App = ({ text }) => <p>{text}</p>; // Passing stringified Date object. ReactDOM.render(<App text={new Date().toString()} />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="app"></div>
p
JSX element.
我将字符串作为p
JSX元素的子代传递。
You need to do something similar and make sure no objects are passed.
您需要执行类似的操作,并确保没有传递任何对象。
Actually, since you didn't post your entire error, it's hard to say which entry is causing the error. 实际上,由于您没有发布整个错误,因此很难说出是哪个条目导致了错误。 But, user.dob
is my best guess. 但是, user.dob
是我的最佳猜测。
Iterating through objects is tricky in React. 在React中遍历对象是棘手的。 Generally you want to use Object.entries
/ Object.values
/ Object.keys
and then .map
. 通常,您要使用Object.entries
/ Object.values
/ Object.keys
然后使用.map
。 This takes the object and creates an array and then you can iterate through the object with .map
. 这将获取对象并创建一个数组,然后可以使用.map
遍历对象。 .map
will not work on an object because it is an array function, so you have to turn your object into an array first. .map
在对象上不起作用,因为它是数组函数,因此必须首先将对象转换为数组。 The .map
function will allow you to iterate in React without that error: .map
函数将允许您在React中进行迭代而不会出现该错误:
this.state = {
branch: "",
name: "",
username: "",
mobile: "",
email: "",
address: ""
}
// Not in your constructor
let myObj = this.state;
Object.entries(myObj).map(item => {
// Successfully iterates, do what you need to do in here
})
Also, it's a very bad idea to use JQuery with React. 另外,在React中使用JQuery是一个非常糟糕的主意。 React uses a virtual DOM and doesn't play well with JQuery. React使用虚拟DOM,因此无法与JQuery配合使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.