This.props undefined React



我有一个问题,我确信它并没有那么复杂,但我对此感到困惑。我已经看过其他堆栈的答案,我仍然很困惑,希望有人能用一双新的眼睛帮助我。我想做的是在点击时返回一个模态。我面临的问题是道具没有定义,当我点击时,我什么也得不到。

const Collection = ({
isLoading,
cues = [],
id,
loadCollection,
onSave,
onRemove,
savedCount,
}) => {
useEffect(() => loadCollection(id), [loadCollection, id]);
const [collection, setCollection] = useState({});
const isMounted = useIsMounted();
const getCollectionData = useCallback(() => {
client.get(`collections/${id}`).then(r => {
if (isMounted.current) setCollection(r.data);
});
}, [id, isMounted, setCollection]);
useEffect(getCollectionData, [id, savedCount]);
return collection.id ? (
<CueList
isLoading={isLoading}
cues={cues}
defaultProps = {cues}
title={collection.name}
description={collection.description}
image={collection.image_src}
isSaved={collection.is_saved}
onSave={() => onSave(id)}
onRemove={() => onRemove(id)}
withVersionsDropdown
buttons={[ 
{
title: 'Share Playlist', //issue is right in here
Icon: props => (
<Share {...props} width={15} height={15} noMargin />
),
onClick: () =>
this.props.onSharePlaylistModal(this.props.playlist),
},
]}
/>
) : (
<Loading />
);
};
Collection.propTypes = {
cues: PropTypes.array,
loadCollection: PropTypes.func.isRequired,
onSave: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired,
id: PropTypes.number.isRequired,
onSharePlaylistModal: PropTypes.func.isRequired,
savedCount: PropTypes.number.isRequired,
};
const mapStateToProps = ({ pageDisplay, cues, sidebar }, { match }) => {
const id = parseInt(match.params.id);
return {
savedCount: sidebar.savedCollections.length,
isLoading: pageDisplay.isLoading,
cues: getCues({
...cues,
sortBy: pageDisplay.sortBy,
sortInBackEnd: false,
}),
id,
};
};
const mapDispatchToProps = (
dispatch,
) => ({
loadCollection: id => {
dispatch(actions.LOAD_COLLECTION(id));
},
onSave: id => {
dispatch(actions.SAVE_COLLECTION(id));
},
onRemove: id => {
dispatch(actions.REMOVE_COLLECTION(id));
},
openSharePlaylistModal: data => {
dispatch(actions.OPEN_MODAL(actions.SHARE_PLAYLIST(undefined, data)));
},
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Collection);

这部分似乎有问题

{
title: 'Share Playlist',
Icon: props => (
<Share {...props} width={15} height={15} noMargin />
),
onClick: () =>
this.props.onSharePlaylistModal(this.props.playlist),
}

目前,当你点击按钮时,控制台中可能有一个错误

由于您在一个功能组件中,因此不希望使用关键字this

道具onSharePlaylistModalplaylist应该可以从参数访问

const Collection = ({
isLoading,
cues = [],
id,
loadCollection,
onSave,
onRemove,
savedCount,
onSharePlaylistModal, // <= here
playlist
}) => {
...

顺便说一句,感觉就像你在看旧的、不推荐使用的react/redux教程,把事情搞混了。

connect是相当老式的,可能最好使用挂钩

this.props用于类组件而非功能组件

最新更新