我正在尝试实现搜索,并且我为输入执行了每次输入文本以搜索输入时都起作用的操作,但是reducer不会触发,而且我不明白为什么以及最奇怪的是,另一种动作和减速器可以正常工作,只有一种无效。
搜索组件
import React, {Component} from 'react'
import './search.css';
import axios from 'axios'
import {getPlayList,setSearchValue} from "./actions";
import {connect} from "react-redux";
class Search extends Component {
state = {
query: '',
results: []
};
getInfo = () => {
this.props.getPlayList(this.state.query);
console.log(this.props.search.searchPlayList);
};
handleInputChange = () => {
/*this.setState({
query: this.search.value
}, () => {
if (this.state.query && this.state.query.length > 1) {
this.getInfo();
}
});*/
setSearchValue(this.search.value);
console.log(this.props.search.searchValue);
};
render() {
return (
<form>
<input
placeholder="Search for..."
ref={input => this.search = input}
onChange={this.handleInputChange}
/>
</form>
)
}
}
const mapStateToProps = store => {
return {
search: store.search
};
};
export default connect(mapStateToProps, {getPlayList,setSearchValue})(Search);
操作方法:
export const getPlayList = (queryParam) => {
return function (dispatch) {
dispatch({type: FETCH_PLAYLIST_REQUEST});
axios.get(`https://cors-anywhere.herokuapp.com/https://api.deezer.com/search/track?q=${queryParam}`).then(response => {
dispatch({
type: FETCH_PLAYLIST_SUCCESS,
payload: {
playlist: response.data.data,
currentTrack: response.data.data[0]
}
});
}).catch(err => {
dispatch({
type: FETCH_PLAYLIST_FAILURE,
payload: err,
});
})
}
};
export const setSearchValue = (value) => {
console.log('setSearchValue',value);
return function (dispatch) {
dispatch({
type: FETCH_SEARCH_VALUE,
payload: value,
});
}
}
减速器
import {
FETCH_PLAYLIST_FAILURE,
FETCH_PLAYLIST_REQUEST,
FETCH_PLAYLIST_SUCCESS,
FETCH_SEARCH_VALUE
} from "../actions/types";
const initialState = {
searchPlayList:null,
currentTrack:null,
searchValue:null,
index: 0,
isLoading: false,
};
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_PLAYLIST_REQUEST:
return {
...state,
isLoading: true
};
case FETCH_PLAYLIST_SUCCESS:
return {
...state,
searchPlayList: action.payload.playlist,
errors: null,
isLoading: false,
};
case FETCH_PLAYLIST_FAILURE:
return {
...state,
errors: action.payload
};
case FETCH_SEARCH_VALUE:
console.log('action.payload',action.payload);
return {
...state,
searchValue: action.payload
};
default:
return state
}
}
答案 0 :(得分:3)
您必须更改此行:
setSearchValue(this.search.value);
对此:
this.props.setSearchValue(this.search.value);
道具中的setSearchValue
将把动作分派到商店。仅仅调用setSearchValue
本身不会做任何事情,因为它尚未连接到redux。