【发布时间】:2019-11-21 14:43:22
【问题描述】:
我正在通过将 redux 与从 Hacker News API 中提取文章的 react 应用一起使用来学习 redux。
我想将搜索栏输入的搜索词保存到redux状态,但是查看状态的时候,redux devtools中我做的searchTerm状态是空的。
这是我的搜索栏组件:
import React, { Component } from 'react'
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import getSearchTerm from '../actions/searchAction';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchTerm: ''
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
onSubmit(e) {
e.preventDefault()
const searchTerm = this.state.searchTerm
this.props.getSearchTerm(searchTerm);
}
render() {
return (
<div>
<form onSubmit={this.onSubmit}>
<input
type="text"
name="searchTerm"
style={{
width: "95%",
paddingTop: 8,
paddingBottom: 8,
paddingLeft: 16,
fontSize: 24
}}
placeholder="Enter term here" onChange={this.onChange}
value={this.state.searchTerm} />
<button type="submit">Submit</button>
</form>
</div>
)
}
}
Search.propTypes = {
searchTerm: PropTypes.string.isRequired
}
const mapPropsToState = state => ({
getSearchTerm: state.searchTerm
})
export default connect(mapPropsToState, { getSearchTerm })(Search)
这是我用来保存搜索词的操作:
export const getSearchTerm = term => dispatch => {
console.log('action called')
dispatch({
type: GET_TERM,
term
})
}
这里是减速器:
import GET_TERM from '../actions/types';
const initState = {
searchTerm: null
}
export default function (state = initState, action = {}) {
switch (action.type) {
case GET_TERM:
return {
searchTerm: action.term
}
default:
return state
}
}
我的控制台也收到警告:
'失败的道具类型:道具
searchTerm被标记为必填项Search,但其值为undefined。'
显然,这意味着我需要的搜索词是未定义的,因为我在 reducer 中将其设置为未定义。但是,我想将我输入的搜索词保存到 redux 状态。我该怎么办?
【问题讨论】:
-
嗯,你没有。 Redux 应该只用于全局状态。搜索输入和保存它们的内容应该在组件的本地状态下进行管理。如果您希望这种情况持续存在,那么也许您应该使用 localStorage。