Redux-form handleSubmit: How to access store state?

前端 未结 4 755
谎友^
谎友^ 2020-12-14 00:59

In a redux-form handleSubmit function, which makes an Ajax call, some properties from the Redux state are needed in the Ajax (e.g. user ID).

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-14 01:35

    This is a variation of @stone's answer, but you can break down option 1 via functional programming:

    const mySubmitHandler = props => values => { /* ...code here */ }
    
    

    In this case, mySubmitHandler will return a function taking only one argument that has already closed over this.props, so there's no need to explicitly mention the values argument that handleSubmit is passing.

    You could perform the currying of mySubmitHandler in a better and more readable way through ramda.

    import { curry } from 'ramda';
    
    const mySubmitHandler = curry((props, values) => { /* ...code here */ });
    

    You can go one step further by composing handleSubmit and mySubmitHandler

    import { compose, curry } from 'ramda';
    
    const handleSubmit = values => { /* ...code here */ };
    const mySubmitHandler = curry((props, values) => { /* ...code here */ });
    const onSubmit = compose(handleSubmit, mySubmitHandler);
    
    
    

    Note that onSubmit(this.props) returns a function that takes one argument (values) and has closed over this.props, creating a function that has access to all the properties it needs!

提交回复
热议问题