我正在尝试通过redux动作将输入值从组件传递给函数。我能够在功能道具中获得价值。但是,道具没有传递到return dispatch =>
函数中。有什么办法可以实现这个目标?
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
}
}
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);
感谢任何人的见识。
答案 0 :(得分:3)
这是正确的方法
const mapDispatchToProps = dispatch => ({
getFilteredCharacters: (input)=>dispatch(getFilteredCharacters(input))
});
或者简单地
const mapDispatchToProps = {getFilteredCharacters}
当前,您正在直接在FilterInput内部调用getFilteredCharacters。为此添加道具参数
const FilterInput = ({ setFilter, getFilteredCharacters }) => {
//...
}