首页 > 解决方案 > 如何从另一个函数更改任何函数组件的状态?

问题描述

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

标签: javascriptreactjsreact-componentreact-state-management

解决方案


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

代替在组件函数之外使用基本函数,我在组件函数内部使用它(在“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>
    </>
  );
}

感谢所有试图以不同方式帮助我的人。


推荐阅读