我有一个搜索框,当我在其中键入内容时,我会触发onChange,在onChange中,我会调用我的redux函数,该函数应该设置;showSearchQuery";在redux存储中传递到字符串,但我总是得到";未定义";。有人能帮忙吗?
以下是有问题的组件/冗余代码:
搜索框组件:
import React from 'react';
import './search-box.styles.css';
import { connect } from 'react-redux';
import { setShowSearchQuery } from '../../redux/actions/index';
class SearchBox extends React.Component {
constructor() {
super();
this.state = {
searchQuery: '',
};
}
handleChange = (event) => {
// console.log('EVENT TARGET VAL', event.target.value);
this.setState({ searchQuery: event.target.value });
let query = this.state.searchQuery;
setShowSearchQuery(query);
};
render() {
return (
<input
type='search'
placeholder={'Search by title'}
onChange={this.handleChange}
/>
);
}
}
const mapStateToProps = (state) => {
return {
showSearchQuery: state.showSearchQuery,
loading: state.loading,
};
};
export default connect(mapStateToProps, { setShowSearchQuery })(SearchBox);
动作:
export const setShowSearchQuery = (data) => {
return {
type: SET_SHOW_SEARCH_QUERY_SUCCESS,
data,
};
};
减速器:
import { setShowSearchQueryUtil } from './shows.utils';
case SET_SHOW_SEARCH_QUERY_SUCCESS:
return {
...state,
showSearchQuery: setShowSearchQueryUtil(action.data),
loading: false,
};
utils函数:
export const setShowSearchQueryUtil = (query) => {
return query;
};
现在,每当我试图访问";showSearchQuery";我总是弄不清楚。
setShowSearchQuery
应该来自道具,因此它应该是handleChange
事件中的this.props. setShowSearchQuery(query)
。
handleChange = (event) => {
// console.log('EVENT TARGET VAL', event.target.value);
this.setState({ searchQuery: event.target.value });
let query = this.state.searchQuery;
this.props.setShowSearchQuery(query);
};
您的Import语句是正确的
import { setShowSearchQuery } from '../../redux/actions/index';
处理中更改:
handleChange = (event) => {
// console.log('EVENT TARGET VAL', event.target.value);
this.setState({ searchQuery: event.target.value });
let query = this.state.searchQuery;
this.props.setShowSearchQuery(query);
};
和
const mapDispatchToProps = dispatch => {
return {
setShowSearchQuery: data => {
dispatch(setShowSearchQuery(data));
}
};
};
const mapStateToProps = (state) => {
return {
showSearchQuery: state.showSearchQuery,
loading: state.loading,
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SearchBox);