将参数从组件传递到动作创建者

时间:2019-09-18 08:19:51

标签: reactjs redux

我真的在Redux上挣扎。我在输入字段中只有一个组件,用户应该输入一个单词,以便将其用作获取请求(在actionCreators文件中)的查询。我将该词设置为状态,因此我想将该词传递给行动,并在获取URL中使用它。

组件:

//controller method
public function office_revenue()
{
    //
    $revenues = Organization::whereOrgId('ALL_SECTORS')->with(['childrenCategories','dataYearOne'])->get();

    //dd($revenues);
    return view('/office-revenue', compact(["revenues"]));
}

//organization model
class Organization extends Model
{
    public function children()
    {
        return $this->hasMany(Organization::class, 'parent_org_id', 'org_id');
    }

    public function childrenCategories()
    {
        return $this->children->with(['childrenCategories','dataYearOne']);
    }

    public function dataYearOne()
    {
        $category = '2020_BUDGET';
        $time = '2018.ACTUAL';
        $amount = $this->hasMany(Data::class)->whereCategoryId(Category::whereCategoryId($category)->value('id'))->whereTimeId(Time::whereTimeId($time)->value('id'));
        if ($this->children->count() > 0)
        {
            foreach($this->children as $child)
            {
                $child->getData($amount, $category, $time);            
            }
            return $amount;
        }
        return $amount;
    }

    public function getData($amount, $category, $time)
    {
        $amount->union($this->hasMany(Data::class)->whereCategoryId(Category::whereCategoryId($category)->value('id'))->whereTimeId(Time::whereTimeId($time)->value('id')));
        foreach($this->children as $child)
        {
            $child->getData($amount, $category, $time);
        }
        return $amount;
    }
}

actionCreators.js:

<button className='search-btn'
        onClick={() => 
this.props.getResults(this.state.searchTerm)}>


const mapDispatchToProps = dispatch => {
    return {
        getResults: (term) => dispatch(getData(term))
    }
}

在reducer中,我将数据设置为action.results。

我只得到export const getData = (term) => { return (dispatch) => { fetch(`...url...${term}`) .then(response => response.json()) .then(data => { console.log(data) dispatch({type: 'GET_DATA', results: data}) }) } }

2 个答案:

答案 0 :(得分:0)

mapDispatchToPropsconnect的第二个参数,第一个是mapStateToProps

default connect (null, mapDispatchToProps)(Search);

Official docs

答案 1 :(得分:0)

这是connect的正确用法。

export default connect(mapStateToProps, mapDispatchToProps)(Search);