gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 04:31:42 27 4
gpt4 key购买 nike

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

我已将客户端移动到上下文中,而不是表格所在的实际页面的状态,但现在我的排序功能当然不再起作用。我需要做的是使用相同的函数,但改为组织处于上下文状态的数组。

原始函数:

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
}
});
};

我的上下文文件:

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;

最佳答案

也许是这样的?

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

因此,value.state 将成为您的状态,value.onSortClient 将成为您的函数。

关于javascript - 将带有 React Context API 的函数传递给嵌套在树深处的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007336/

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