gpt4 book ai didi

javascript - 如何从另一个函数更改任何函数组件的状态?

转载 作者:行者123 更新时间:2023-11-28 17:00:01 26 4
gpt4 key购买 nike

React 16.8 将状态和 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 组件的状态(产品)。

最佳答案

最后我想出了一个简单的解决方案。

我不是在组件函数外部使用基本函数,而是在组件函数内部使用它(“fetch_all_products”在“Shop”内部使用)。

[我的问题中有一个愚蠢的语法错误,此处也已更正]

代码:

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 - 如何从另一个函数更改任何函数组件的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57783064/

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