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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52007336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:47:03  来源:igfitidea点击:

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

javascriptreactjsreact-props

提问by acd37

I'm using React Context API for the first time. 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.

我是第一次使用 React Context API。我有一个生成客户列表的表。最初,我将客户端存储在一个数组中,在同一页面中,我有一个基于点击对客户端进行排序的函数。

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;

回答by devserkan

Maybe something like that?

也许是这样的?

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

So, value.statewill be your state, value.onSortClientwill be your function.

所以,value.state将是你的状态,value.onSortClient将是你的功能。