Trying to dispatch a delete event from a button inside a nested component.
I passed the dispatch as a property to the component from App.js like so
render() {
const {files, isFetching, dispatch} = this.props;
const isEmpty = files.length === 0;
return (
<div>
<h1>Uploadr</h1>
{isEmpty
? (isFetching ? <h2>Loading...</h2> : <h2>No files.</h2>)
: <div style={{opacity: isFetching ? 0.5 : 1}}>
<Files files={files} dispatch={dispatch}/>
</div>
}
</div>
)
}
Inside the nested component I call dispatch from an onclick
attribute
const Files = ({files, dispatch}) => (
<ul>
{files.map((file, i) =>
<li key={i}>{file.name}
<button onClick={dispatch(deleteFileById(file.id))}>Delete</button>
</li>
)}
</ul>
);
Files.propTypes = {
files: PropTypes.array.isRequired,
dispatch: PropTypes.func.isRequired
};
export default Files
This is the method being called
export const deleteFileById = (dispatch, fileId) => {
dispatch(deleteFile);
return fetch(`/api/files/${fileId}`, {method : 'delete'})
.then(dispatch(fetchFiles(dispatch)))
};
I tried doing this.props.dispatch
however this did not work either.
Any ideas?
Seems like your method deleteFileById
expects the dispatcher as an argument. Does the following adjustment work for you?
<button onClick={() => (deleteFileById(dispatch, file.id))}>Delete</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.