简体   繁体   English

无法从 mapsDispatchToProps 访问“道具”

[英]Can't access "props" from mapsDispatchToProps

I am trying to pass an input value from my component to a function in my redux actions.我正在尝试将输入值从我的组件传递给我的 redux 操作中的函数。 I am able to get the value in the function props.我能够获得函数道具中的值。 However, the props aren't passing into the return dispatch => function.但是,道具没有传递到return dispatch =>函数中。 Is there any way to accomplish this goal?有没有办法实现这个目标?

actions.js动作.js

function fetchData(url){
  return fetch(url)
            .then(res => res.json())
            .catch(console.log())
}

export function getFilteredCharacters(input) {
  console.log(input); //Shows props in console
  return (dispatch) => {

    console.log(chars); //Doesn't show props in console
    for (let i=1; i<=9; i++) {
      requests.push(fetchData('https://swapi.co/api/people/?page=' + i));
    }

    Promise.all(requests)
    .then(data => {
      let charactersAll = [];
      let characterFiltered = [];
      for (let i=0; i<=8; i++) {
        charactersAll.push(...data[i].results);
      }
      for (let i=0; i < charactersAll.length; i++) {
        if (charactersAll[i].name.includes(input)) { // This is where I need the props.
          characterFiltered.push(charactersAll[i]);
        }
      }
      dispatch(setFilteredCharacters(characterFiltered));
    })
  }
}

export function setFilteredCharacters(characterFiltered) {
  return {
    type: SET_CHARACTERS_FILTERED,
    characterFiltered
  }
}

components/FilterInput.js组件/FilterInput.js

import React from 'react';
import { connect } from 'react-redux';
import { getFilteredCharacters } from '../reducer/character/actions';


const FilterInput = ({ setFilter }) => {

  return (
    <div class="input-group">
      <div class="input-group-prepend">
        <span class="input-group-text">Name</span>
      </div>
      <input type="text" aria-label="Name" className="form-control" onChange={e => getFilteredCharacters(e.target.value)} />
    </div>
  )
};

const mapDispatchToProps = dispatch => ({
  getFilteredCharacters(input) {}
});

export default connect(null, mapDispatchToProps)(FilterInput);

Thanks to anyone for insight.感谢任何人的洞察力。

This is the correct way这是正确的方法

const mapDispatchToProps = dispatch => ({
  getFilteredCharacters: (input)=>dispatch(getFilteredCharacters(input))
});

Or simply或者干脆

const mapDispatchToProps = {getFilteredCharacters}

Currently you are calling to getFilteredCharacters directly inside FilterInput.目前,您正在直接在 FilterInput 中调用 getFilteredCharacters。 Add a props argument for it为它添加一个 props 参数

const FilterInput = ({ setFilter, getFilteredCharacters }) => {
//...
}

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

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