gpt4 book ai didi

javascript - 在 React 中更新组件数据

转载 作者:行者123 更新时间:2023-11-30 19:00:42 25 4
gpt4 key购买 nike

我有以下组件结构。

<Dashboard>
<UserData />
<MealList />
<Search />
</Dashboard>

我正在仪表板内使用 useEffects 获取 UserDataMealList 的内容,并将它们作为 props 传递下去。

const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [calories, setCalories] = useState("");
const [meals, setMeals] = useState([]);

useEffect(async () =>{
const data = await fetchUserData(localStorage.getItem('email'));
localStorage.setItem('user_id', data['id']);
setUsername(data['username']);
setEmail(data['email']);
setCalories(data['calories']);
const mealsData = await fetchMeals(localStorage.getItem('user_id'));
setMeals([...meals, ...mealsData]);

}, []);

现在我要实现的是基于餐单刷新的搜索参数。

我正在从搜索组件中获取搜索参数并将其传递回 MealList

然后我进行 REST 调用并获取更新后的数据。

const updateList = async ( ft, tt, fd, td) =>{
const userId = localStorage.getItem('user_id');
const updatedMealsList = await searchMeals(userId, ft, tt, fd, td);
console.log('Updated Meals', updatedMealsList);
setMeals([]);//Tried this but doesn't work
setMeals([...meals, ...updatedMealsList]);//
};

我的问题是如何更新 Meallist 数组并重新渲染组件?

我已经试过了,还是不行。我所说的不起作用的意思是 meals 数组中的数据既没有更新也没有被重新呈现。

这是组件。

const Dashboard = () => {
const [username, setUsername] = useState("");
const [email, setEmail] = useState("");
const [calories, setCalories] = useState("");
const [meals, setMeals] = useState([]);

useEffect(async () =>{
const data = await fetchUserData(localStorage.getItem('email'));
localStorage.setItem('user_id', data['id']);
setUsername(data['username']);
setEmail(data['email']);
setCalories(data['calories']);
const mealsData = await fetchMeals(localStorage.getItem('user_id'));
setMeals([...meals, ...mealsData]);

}, []);


const updateList = async ( ft, tt, fd, td) =>{
const userId = localStorage.getItem('user_id');
const updatedMealsList = await searchMeals(userId, ft, tt, fd, td);
setMeals([]);
console.log('Updated Meals', updatedMealsList);
setMeals([...meals, ...updatedMealsList]);
};
console.log('Updated Meals', meals);
return (
<div>
<Navigation/>
<div className="wrapper">
<div style={{display: 'flex', flexFlow: 'row wrap'}}>
<UserData username={username} email={email} calories={calories}/>
<Search onSubmit={updateList}/>
</div>
<MealList meals={meals}/>

</div>

</div>

)
};
export default Dashboard;

餐单

const MealList = (props) => {
return (
<div style={{width: '70%'}}>
<h3 style={{color: 'grey', fontSize: '1.4em', fontWeight: '700', marginBottom: '1em'}}><FontAwesomeIcon
icon={faPlusCircle} style={{color: '#007bff', marginRight: '0.5em'}}/> ADD MEAL</h3>
<Table striped bordered hover>
<thead>
<tr>
<th>#</th>
<th>Meal</th>
<th>Calories</th>
<th>Time</th>
<th>Date</th>
<th>Update</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{props.meals.map((meal, index) => (<Meal count={index +1} meal={meal}/>))}
</tbody>
</Table>
</div>

)
};
export default MealList;

最佳答案

首先,我建议你阅读下面的文章

https://overreacted.io/a-complete-guide-to-useeffect/

这里详细解释了如何正确使用useEffect hook

let dynamicMealId = 3;
function delay(payload) {
return new Promise((resolve) => {
window.setTimeout(() => {
resolve(payload)
}, 350)
})
}

function fetchUserData(email) {
return delay({
id: Date.now(),
username: 'johndoe@doe.com',
calories: 2000
})
}

function fetchMeals(userId) {
return delay([{
id: 1,
name: 'Meal 1'
}, {
id: 2,
name: 'Meal 2'
}, {
id: 3,
name: 'Meal 3'
}])
}

function searchMeals(userId, filters) {
return delay(Array.from({length: 3}, (v, k) => k+1).map(function () {
const meal = {
id: dynamicMealId,
name: 'Meal ' + dynamicMealId
}
dynamicMealId++;
return meal;
}))
}

function UserData(props) {
return (
<div>
{props.user ? (
<React.Fragment>
<h1>UserData</h1>
<div>{props.user.username}</div>
<div>{props.user.calories}</div>
</React.Fragment>
) : (
<span>Loading User...</span>
)}
</div>
);
}

function Search(props) {

function handleSubmit(ev) {
ev.preventDefault()
props.onSearch(ev.target.elements[0].value);

}

return (
<form onSubmit={handleSubmit}>
<h1>Search</h1>
<label forHtml="input">
Enter Keyword
</label>
<input type="text" id="input"/>
</form>
)
}

function MealList(props) {
console.log(props.meals)
return (
<div>
<h1>MealList</h1>
<ul>
{props.meals.map(function(meal) {
return (
<li key={meal.id}>{meal.name}</li>
)
})}
</ul>
</div>
)
}


const Dashboard = () => {
const [user, setUser] = React.useState(null)
const [meals, setMeals] = React.useState(null)
const [filters, setFilters] = React.useState(null)

// loads user data
React.useEffect(() => {
function loadData() {
fetchUserData('some@email.com')
.then((userData) => {
setUser(userData);
return fetchMeals(userData.id)
})
.then((userMeals) => {
setMeals(userMeals);
});
}

loadData();
}, []);

// loads new meals
React.useEffect(() => {
if (!user || !filters) { return; }

function search() {
searchMeals(user.id, filters)
.then(newMeals => {
setMeals(currentMeals => [
...currentMeals,
...newMeals
])
})
}

search();
}, [user, filters]);



return (
<div>
Dashboard
<UserData user={user}/>
{user && meals && (
<div>
<Search onSearch={newFilters => setFilters(newFilters)} />
<MealList
meals={meals}
/>
</div>
)}
</div>
)
}



ReactDOM.render(
<Dashboard />,
document.querySelector('#app')
)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.11.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>
</head>
<body>
<div id="app"></div>
</body>
</html>

关于javascript - 在 React 中更新组件数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59537286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com