问题
I am making react project using express.js, mongodb, react.js, and node.js. and trying to fetch data from backend api which is running on port 5000.
When I check the api using postman
, it is working. And the data is showing in the browser's console. Also, when I press Get
button as given in the code below, it doesn't work on the browser. But I'm able to see the array data in the browser's console.
<Button onClick={()=><li>{employeeItem}</li>}>Get</Button>
Here is my full code:
import React, { Component } from "react";
import {
form,
FormGroup,
FormControl,
ControlLabel,
Button
} from "react-bootstrap";
import "./App.css";
import { stringify } from "querystring";
class App extends Component {
constructor(props) {
super(props);
this.AddName = this.AddName.bind(this);
this.AddContact = this.AddContact.bind(this);
this.AddAge = this.AddAge.bind(this);
this.state = {
name: "",
contact: "",
age: "",
employees: []
};
}
AddName(e) {
this.setState({ name: e.target.value });
}
AddContact(e) {
this.setState({ contact: e.target.value });
}
AddAge(e) {
this.setState({ age: e.target.value });
}
componentWillMount() {
fetch("http://localhost:5000/api/employees")
.then(res => res.json())
.then(data => this.setState({ employees: data }));
}
render() {
const employeeItem = this.state.employees.map(employee => (
<div key={employee._id}>
<h3>{employee.name}</h3>
<p>{employee.contact}</p>
<p>{employee.age}</p>
</div>
));
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Employee List</h1>
</header>
<div className="Layout">
<form>
<FormGroup>
<ControlLabel>Name:</ControlLabel>
<FormControl
type="text"
value={this.state.name}
placeholder="Employee name"
onChange={this.AddName}
/>
<div>
<ControlLabel>Contact:</ControlLabel>
<FormControl
type="number"
value={this.state.contact}
placeholder="Mobile number"
onChange={this.AddContact}
/>
</div>
<div>
<ControlLabel>Age:</ControlLabel>
<FormControl
type="number"
value={this.state.age}
placeholder="Age"
onChange={this.AddAge}
/>
</div>
</FormGroup>
<Button type="submit">Add</Button>
<Button onClick={() => console.log({ employeeItem })}>Get</Button>
<Button type="submit">Delete</Button>
</form>
</div>
</div>
);
}
}
export default App;
on running page
回答1:
You can't render an item as you are trying inside an onClick
callback. You can render the items immediately after fetched them or you can trigger with an onClick
the fetch or you can hide and show the items.
Immediately rendering
const employees = [
{ _id: 1, name: "foo", contact: "abc", age: 20 },
{ _id: 2, name: "bar", contact: "efg", age: 30 },
{ _id: 3, name: "baz", contact: "hij", age: 40 }
];
const fakeRequest = () =>
new Promise(resolve => setTimeout(() => resolve(employees), 1000));
class App extends React.Component {
state = {
employees: []
};
componentDidMount() {
fakeRequest().then(employees => this.setState({ employees }));
}
render() {
const employees = this.state.employees.map(employee => (
<div style={{ border: "1px solid black" }} key={employee._id}>
<h3>Name: {employee.name}</h3>
<p>Contact: {employee.contact}</p>
<p>{employee.age}</p>
</div>
));
return (
<div>
<p>Data will be fetched in a second automatically.</p>
{employees}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Get with a button click
const employees = [
{ _id: 1, name: "foo", contact: "abc", age: 20 },
{ _id: 2, name: "bar", contact: "efg", age: 30 },
{ _id: 3, name: "baz", contact: "hij", age: 40 },
];
const fakeRequest = () => new Promise( resolve =>
setTimeout( () => resolve( employees ), 1000)
);
class App extends React.Component {
state = {
employees: [],
};
getEmployees = () =>
fakeRequest()
.then(employees => this.setState({ employees }))
render() {
const employees = this.state.employees.map(employee => (
<div style={{ border: "1px solid black"}} key={employee._id}>
<h3>Name: {employee.name}</h3>
<p>Contact: {employee.contact}</p>
<p>{employee.age}</p>
</div>
));
return (
<div>
<p>Data will be fetched after the button click.</p>
<button onClick={this.getEmployees} >Get Employees</button>
{employees}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Show/hide method
const employees = [
{ _id: 1, name: "foo", contact: "abc", age: 20 },
{ _id: 2, name: "bar", contact: "efg", age: 30 },
{ _id: 3, name: "baz", contact: "hij", age: 40 },
];
const fakeRequest = () => new Promise( resolve =>
setTimeout( () => resolve( employees ), 1000)
);
class App extends React.Component {
state = {
employees: [],
showEmployees: false,
};
componentDidMount() {
fakeRequest()
.then(employees => this.setState({ employees }))
}
toggleEmployees = () => this.setState( prevState => ({
showEmployees: !prevState.showEmployees,
}))
render() {
const { showEmployees } = this.state;
const employees = this.state.employees.map(employee => (
<div style={{ border: "1px solid black"}} key={employee._id}>
<h3>Name: {employee.name}</h3>
<p>Contact: {employee.contact}</p>
<p>{employee.age}</p>
</div>
));
return (
<div>
<p>Data will be fethced automatically in a second but will be hidden by default. Button click toggles this state.</p>
<button
onClick={this.toggleEmployees}
>
{
showEmployees ? "Hide Employees" : "Show Employees"
}
</button>
{this.state.showEmployees && employees}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
来源:https://stackoverflow.com/questions/52249012/how-to-display-data-coming-from-mongodb-to-reactjs-after-clicking-the-button