gpt4 book ai didi

javascript - Action 不触发reducer

转载 作者:行者123 更新时间:2023-11-28 17:26:56 26 4
gpt4 key购买 nike

我正在尝试实现搜索,并且我执行了输入操作,每次当我输入文本进行搜索输入时,该操作都有效,但是 reducer 不会触发,我不明白为什么,最奇怪的是,另一种操作和 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,
});
}
}

reducer

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
}
}

以及它是如何工作的 enter image description here

最佳答案

您必须更改此行:

setSearchValue(this.search.value);

对此:

this.props.setSearchValue(this.search.value);

props 中的 setSearchValue 会将操作分派(dispatch)到存储。仅调用 setSearchValue 本身不会执行任何操作,因为它尚未连接到 redux。

关于javascript - Action 不触发reducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51340615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com