简体   繁体   English

类型错误:调度不是嵌套组件中的函数

[英]TypeError: dispatch is not a function in nested component

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我像这样将调度作为属性从 App.js 传递给组件

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在嵌套组件中,我从onclick属性调用 dispatch

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.我尝试做this.props.dispatch但这也不起作用。

Any ideas?有任何想法吗?

Seems like your method deleteFileById expects the dispatcher as an argument.似乎您的方法deleteFileById期望调度程序作为参数。 Does the following adjustment work for you?以下调整对您有用吗?

<button onClick={() => (deleteFileById(dispatch, file.id))}>Delete</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM