我开发了一个小应用程序,目的是研究反应钩子。该应用程序包括在一个部分中写入艺术家的姓名。在下一部分,一个类似的表格,用于填写每个艺术家的专辑。
我将所有组件以及上下文、状态和减速器都分开了。我对每个艺术家、专辑和歌曲都有单独的上下文。当我单击艺术家按钮时,我想过滤专辑以便只出现他们的专辑。但是使用减速器调度两次,在控制台日志中它告诉我两者都来自减速器文件。
有趣的是,第一次点击时,我只经过一次,但第二次我看到我选择了两次调度艺术家。
另一个有趣的事情是,当我更改选定的艺术家时,它会删除状态专辑,这是我拥有所有专辑的地方。它不会过滤它们,但会删除它们。
这是我单击以调用每个艺术家的 id 并将当前选择的艺术家发送到艺术家上下文和专辑上下文的表单
import React, { useContext } from "react";
import AlbumContext from "../../context/Album/AlbumContext";
import ArtistContext from "../../context/Artist/ArtistContext";
const Artist = ({ item }) => {
const albumContext = useContext(AlbumContext);
const { getArtist } = albumContext;
const artistContext = useContext(ArtistContext);
const { artist, getselectedArtist } = artistContext;
const handleSelect = (artist_id) => {
getArtist(artist_id);
getselectedArtist(artist_id);
};
return (
<>
<div
style={{ border: "1px solid black", margin: "10px", padding: "5px" }}
>
<p>{item.name}</p>
<button type="button">Edit</button>
<button type="button">Delete</button>
<button type="button" onClick={() => handleSelect(item.id)}>
Select
</button>
</div>
</>
);
};
export default Artist;
第二个是 ALBUMSTATE,我调用函数 getArtist 来调度并获取该选定艺术家的所有专辑
import React, { useReducer } from "react";
import AlbumContext from "./AlbumContext";
import AlbumReducer from "./AlbumReducer";
import { GET_ARTIST, ADD_ALBUM, VALIDATE_FORM } from "../../types";
const AlbumState = (props) => {
const initialState = {
albums: [],
errorform: false,
selectedartist: "",
};
const [state, dispatch] = useReducer(AlbumReducer, initialState);
//-----METHODS-----//
const addAlbum = (album) => {
dispatch({
type: ADD_ALBUM,
payload: album,
});
};
const setError = (error) => {
dispatch({
type: VALIDATE_FORM,
payload: error,
});
};
const getArtist = (id) => {
dispatch({
type: GET_ARTIST,
payload: id,
});
};
return (
<AlbumContext.Provider
value={{
selectedartist: state.selectedartist,
albums: state.albums,
errorform: state.errorform,
addAlbum,
setError,
getArtist,
}}
>
{props.children}
</AlbumContext.Provider>
);
};
export default AlbumState;
这是 ALBUMREDUCER
import { GET_ARTIST, ADD_ALBUM, VALIDATE_FORM } from "../../types";
export default (state, action) => {
switch (action.type) {
case ADD_ALBUM:
return {
...state,
albums: [action.payload, ...state.albums],
};
case VALIDATE_FORM:
return {
...state,
errorform: action.payload,
};
case GET_ARTIST:
console.log(action.payload);
return {
...state,
selectedartist: action.payload,
albums: state.albums.filter(
(album) => album.artist_creator === action.payload
),
};
return {
...state,
selectedartist: action.payload,
};
default:
return state;
}
};