简体   繁体   English

将具有React Context API的函数传递给嵌套在树中深处的子组件

[英]Passing a function with React Context API to child component nested deep in the tree

I'm using React Context API for the first time. 我第一次使用React Context API。 I have a table that generates a list of clients. 我有一个表生成客户列表。 Originally, I stored the clients in an array in state, and in the same page I had a function that sorted the clients based on click. 最初,我将客户端存储在一个状态的数组中,并且在同一页面中,我有一个根据点击对客户端进行排序的功能。

I have moved the clients into context rather than in state of the actual page where the table is, but now of course my sort function no longer works. 我已经将客户端移动到上下文而不是表格的实际页面的状态,但现在我的排序函数当然不再有效。 What I need to be able to do is use the same function, but organize the array that is in the context state instead. 我需要做的是使用相同的函数,但组织处于上下文状态的数组。

Original function: 原功能:

onSortClient = column => e => {
        const direction = this.state.sort.column
            ? this.state.sort.direction === "asc"
                ? "desc"
                : "asc"
            : "desc";
        const sortedData = this.state.clients.sort((a, b) => {
            if (column === "client_name") {
                const nameA = a.client_name.toUpperCase();
                const nameB = b.client_name.toUpperCase();
                if (nameA < nameB) {
                    return -1;
                }
                if (nameA > nameB) {
                    return 1;
                }

                return 0;
            }
            return 0;
        });

        if (direction === "desc") {
            sortedData.reverse();
        }

        this.setState({
            clients: sortedData,
            sort: {
                column,
                direction
            }
        });
    };

My context file: 我的上下文文件:

import React, { Component } from "react";
import axios from "axios";

const Context = React.createContext();

const Reducer = (state, action) => {
    switch (action.type) {
        case "DELETE_CLIENT":
            console.log(action.payload);
            return {
                ...state,
                clients: state.clients.filter(client => client.id !== action.payload)
            };
        case "ADD_CLIENT":
            return {
                ...state,
                clients: [action.payload, ...state.clients]
            };
        case "UPDATE_CLIENT":
            console.log(action.payload);
            return {
                ...state,
                clients: state.clients.map(
                    client =>
                        client.id === action.payload.id ? (client = action.payload) : client
                )
            };

        default:
            return state;
    }
};

export class Provider extends Component {
    state = {
        clients: [],
        loaded: false,
        dispatch: action => {
            this.setState(state => Reducer(state, action));
        }
    };

    async componentDidMount() {
        let localToken = localStorage.getItem("iod_tkn");

        const res = await axios({
            url: "/users/get_clients",
            method: "get",
            headers: {
                Authorization: localToken
            }
        });

        this.setState({
            clients: res.data,
            loaded: true
        });
    }


    render() {
        return (
            <Context.Provider onSortClient={this.onSortClient} value={this.state}>
                {this.props.children}
            </Context.Provider>
        );
    }
}

export const Consumer = Context.Consumer;

Maybe something like that? 也许是这样的?

<Context.Provider
    value={{
        state: this.state,
        onSortClient: this.onSortClient,
    }}
>
    {this.props.children}
</Context.Provider>

So, value.state will be your state, value.onSortClient will be your function. 所以, value.state将是你的状态, value.onSortClient将是你的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将带有 React Context API 的函数传递给嵌套在树深处的子组件以更新状态值 - Passing a function with React Context API to child component nested deep in the tree to update state value React Child组件无法访问上下文API - React Child component cant access the context API 反应-将功能传递给子组件没有任何作用 - React - passing a function to a child component does nothing 在嵌套组件反应js中在子组件和父组件之间传递数据 - passing data between child and parent component in nested component react js 我们如何提高使用递归组件呈现深层嵌套树数据的 React 应用程序的性能 - How do we improve the performance of a react application which renders the the deep nested tree data with a recursive component 将 props 传递给嵌套的子组件 - Passing props to nested child component 反应上下文; 子组件不重新渲染 - React context; child component not rerendering 将 function 作为道具传递给 React 中的子组件会引发错误 - passing function as a prop to child component in React throws error 反应本机连接功能不通过prop将动作传递给子组件 - React native connect function not passing action to child component through props 将数据从子级传递到父级组件-反应-通过回调函数 - passing data from child to parent component - react - via callback function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM