首页 > 解决方案 > 如何在reactjs中将值从输入框传递到reducer

问题描述

我只是创建了一个简单的 redux 项目,我面临着我不知道的新事物,cz 我是 reactJS 的新手,它是如何从 reducer 传递值以便用我传递的新值替换 globalstate,

    //Global State
    const initialstate = {
       nameOrder : ''
    }

   // Reducer Action
   const rootReducer = (state = initialstate ,action) => 
   {
    console.log(action.value)
    if(action.type === 'CHANGE'){
       return{
      ...state,
         nameOrder : action.value

        }
      }
    return state;
  }

//Store
const storeroot = createStore(rootReducer);

这是我的代码来传递我想要的值

render() {
        console.log(this.props);
        return (
            <div>
                <Card width="50%">
                    <CardHeader>
                        {this.props.order}
                    </CardHeader>
                    <CardBody>
                        <Form inline>
                            <FormGroup>
                                <Label  >Desc1</Label>
                                <Input onChange={this.HandleChange1} />
                            </FormGroup>
                            <FormGroup>
                                <Label  >Desc2</Label>
                                <Input onChange={this.HandleChange2} />
                            </FormGroup>
                            <FormGroup>
                                <Label>Harga</Label>
                                <Input onChange={this.onChangePrice}/>
                            </FormGroup>
                            <Button onClick={this.props.ubah}>Submit</Button>
                        </Form>
                    </CardBody>
                    <CardFooter>
                    </CardFooter>
                </Card>
            </div>
        )
    }


const mapStatetoProps = (state) =>{
    return{
        order : state.totalOrder
    }
}

const mapDispatchtoProps = (dispatch) =>{
    return{
        ubah:() => dispatch({type: 'CHANGE',value:this.state.desc1})
    }
}
export default connect(mapStatetoProps,mapDispatchtoProps)(Addform)

在 mapDispatchtoProps this.state.desc1中抛出错误,谁能帮我解决这个问题

标签: reactjsreact-redux

解决方案


答案很简单。

 ubah:() => dispatch({type: 'CHANGE',value:this.state.desc1})

在上面的语句中,this 指针没有被定义。您必须将值作为参数传递。

 ubah:(description) => dispatch({type: 'CHANGE',value:description})

当您使用该函数进行事件处理时,您必须像下面的代码一样调用它:

<Button onClick={() => this.props.ubah(this.state.desc1)}>Submit</Button>

推荐阅读