javascript - 如何从另一个函数更改任何函数组件的状态?
问题描述
React 16.8 将 state 和 setState 功能带入了基于函数的组件中。
我的问题是:
在基于函数的组件的情况下,有没有办法改变函数之外的状态?
示例:
import {useState} from 'react';
import Axios from 'axios';
function fetch_all_products(){
Axios.get(url)
.then(
response => {
let data = response.data;
//FROM HERE I WANT TO SET THIS DATA INTO SHOP COMPONENT
// STATE (i.e, products) AND RE RENDER THE SHOP COMPONENT
}
)
}
export default function Shop(){
const[products, setProducts] = useState(products['Rice','Oil']);
let all_products = products.map( product => {
return(
<li>product</li>
)
});
return(
<>
<h2>The Grocery Shop </h2>
<button onClick={fetch_all_products}>See All Products </button>
<ul>
{all_products}
</ul>
</>
)
}
我想通过使用 'fetch_all_products' 函数在函数外更改 Shop 组件的状态(产品)。
解决方案
最后我想出了一个简单的解决方案。
代替在组件函数之外使用基本函数,我在组件函数内部使用它(在“Shop”内部使用“fetch_all_products”)。
[我的问题中有一个愚蠢的句法错误,这里也更正了]
代码:
import { useState } from 'react';
import Axios from 'axios';
export default function Shop() {
const [products, setProducts] = useState(['Rice', 'Oil']);
function fetch_all_products() {
Axios.get(url).then((response) => {
let data = response.data;
setProducts(data);
});
}
let all_products = products.map((product) => <li>{product}</li>);
return (
<>
<h2>The Grocery Shop </h2>
<button onClick={fetch_all_products}>See All Products </button>
<ul>{all_products}</ul>
</>
);
}
感谢所有试图以不同方式帮助我的人。
推荐阅读
- javascript - 如何使用 Selenium Java 将按钮标签插入 html?
- javascript - 如何使用root更改css背景图像
- r - 在 R 中调整图形和图例
- amazon-web-services - AWS 工作区 msi 部署
- facebook-graph-api - Facebook 图形 API AdsActionsStats
- sql-server - Adventure Works 2019:向 Person.Person 表添加新人员
- mysql - 如果日期介于第二个表的日期之间,则使用第一个表中的日期从第二个表中获取列
- html - 仅对文本产生窗帘效果 - 文本从中间到外边缘显示
- python - 如何使用python循环遍历JSON数据?
- c# - 我如何在sqlite中存储日期值