英文:
Display multiple values from file in React
问题
我正在尝试使用React显示一个待办事项清单。所以我正在加载一个看起来像这样的json文件:
{
"todos":
[{"id":1,"todo":"为我关心的人做点好事","completed":true,"userId":26},
{"id":2,"todo":"记住五十个州及其首府","completed":false,"userId":48},
{"id":3,"todo":"看一部经典电影","completed":false,"userId":4}],
"total":150,"skip":0,"limit":30
}
而且我也在使用mui的复选框。所以我想显示一个复选框,当"completed"为true时,它的"defaultChecked"应该为开启状态。
我成功加载了json并显示了复选框,但我无法弄清楚如何全部显示它们。
代码:
```javascript
import './App.css';
import React, { Component } from 'react';
import { Checkbox, FormControlLabel, FormGroup } from '@mui/material';
import data from './todo-list.json';
function App() {
for(let i = 0; i < data.todos.length; i++) {
if(data.todos[i].completed) {
var checkbox = console.log(data.todos[i].id, data.todos[i].todo);
}
else {
console.log(data.todos[i].id, data.todos[i].todo);
}
}
return (
<div>
<header>
<FormGroup>
<FormControlLabel control={<Checkbox defaultChecked />} label="Label" />
<FormControlLabel control={<Checkbox />} label="Label 2" />
</FormGroup>
</header>
</div>
);
}
export default App;
英文:
I'm trying to display a checklist using React. So I'm loading a json file that looks something like this:
{
"todos":
[{"id":1,"todo":"Do something nice for someone I care about","completed":true,"userId":26},{"id":2,"todo":"Memorize the fifty states and their capitals","completed":false,"userId":48},{"id":3,"todo":"Watch a classic movie","completed":false,"userId":4}]
,"total":150,"skip":0,"limit":30
}
And I'm also using mui's checkboxes. So I want to display a checkbox and its "defaultChecked" should be on when "completed" is true.
I managed to load the json and display checkboxes, but I cant figure out how to display all of them.
Code:
import './App.css';
import React, { Component } from 'react';
import { Checkbox, FormControlLabel, FormGroup } from '@mui/material';
import data from './todo-list.json';
function App() {
for(let i = 0; i < data.todos.length; i++) {
if(data.todos[i].completed) {
var checkbox = console.log(data.todos[i].id, data.todos[i].todo);
}
else {
console.log(data.todos[i].id, data.todos[i].todo);
}
}
return (
<div>
<header>
<FormGroup>
<FormControlLabel control={<Checkbox defaultChecked />} label="Label" />
<FormControlLabel control={<Checkbox />} label="Label 2" />
</FormGroup>
</header>
</div>
);
}
export default App;
I managed to load the json and display checkboxes, but I cant figure out how to display all of them.
答案1
得分: 0
你需要映射你的待办事项并相应地呈现。
你的返回应该像这样:
return (
<div>
<header>
<FormGroup>
{data.todos.map(todo => <FormControlLabel control={<Checkbox checked={todo.completed} />} label={todo.todo} /> )}
</FormGroup>
</header>
</div>
);
英文:
You need to map on your todos and render accordingly.
Your return should look like this.
return (
<div>
<header>
<FormGroup>
{data.todos.map(todo => <FormControlLabel control={<Checkbox checked={todo.completed} />} label={todo.todo} /> )}
</FormGroup>
</header>
</div>
);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论