【问题标题】:ReactJS - How to pass state data and functions from one functional component to other component?ReactJS - 如何将状态数据和函数从一个功能组件传递到另一个组件?
【发布时间】:2020-12-10 12:29:37
【问题描述】:

在 react 应用程序中,我尝试将 react-reduxhooks 与基本的 CRUD、对象数组的搜索和排序操作一起使用。

我的主要组件是使用类似导入的功能组件

import React, { useState, useEffect } from 'react';
import { createStore } from 'redux';
import reducer from './reducer';
const store = createStore(reducer);

function Friends(props) {
  const [friends, setFriends] = useState(store.getState().friends);
  ...
}

我要访问Friends 组件内的store 就像,

 function deleteFriend(id) {
   store.dispatch({type: 'DELETE_FRIEND', friendId: id});
   setFriends(store.getState().friends);
 }

 function onSortClick() {
   store.dispatch({ type: 'SORT_FRIENDS' });
   setFriends(store.getState().friends);
 }

<Route path="/list">
  <List result={friends} onSortClick={onSortClick} onDeleteClick={deleteFriend} />
</Route>

现在的问题是,在对数组进行排序时,我在当前组件 (console.log(friends);) 中得到了更新的 friends,但在 List 组件中我没有得到它作为 props.result

请帮我解决这个问题?

【问题讨论】:

    标签: arrays reactjs redux react-hooks react-props


    【解决方案1】:

    当组件处于路由下时,请单独使用 Redirect 选项和所需条件(例如:{isChecked &amp;&amp; &lt;Ridirect ... /&gt; })。

    <Redirect to="/list">
       <List result={friends} onSortClick={onSortClick} onDeleteClick={deleteFriend} />
    </Redirect>
    

    这样,将通过重新渲染&lt;List&gt; 组件来进行排序。

    虽然我是 reactjs 新手,但我自己找到了这个答案。如果有任何其他解决方案/建议,请告诉我。

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2020-03-12
      • 2020-05-27
      • 2022-11-01
      • 2021-01-02
      • 2019-12-11
      相关资源
      最近更新 更多