acd*_*d37 7 javascript reactjs react-props
我第一次使用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
}
});
};
Run Code Online (Sandbox Code Playgroud)
我的上下文文件:
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;
Run Code Online (Sandbox Code Playgroud)
dev*_*kan 13
也许是这样的?
<Context.Provider
value={{
state: this.state,
onSortClient: this.onSortClient,
}}
>
{this.props.children}
</Context.Provider>
Run Code Online (Sandbox Code Playgroud)
那么,value.state将是你的状态,value.onSortClient将是你的功能.
| 归档时间: |
|
| 查看次数: |
8111 次 |
| 最近记录: |