我有一个 React / Redux (使用打字稿)应用程序,可以从服务器端获取用户列表。当用户尝试通过添加的输入文本进行过滤时,当我尝试再次请求用户列表时,问题就来了。该操作从不从用户那里获取数据(用户过滤器),因此我得到了开始时未过滤的用户列表。
操作
export const getUsers = (data?: UserFiltersState) => {
const url = encodeQueryData(data)
return {
type: UserActionTypes.GET_USERS,
payload: fetch('app/admin/user/search/multisearch' + url)
.then(res => res.json())
.then(json => json)
.catch(ex => {
console.log('users request error.', ex)
return []
})
}
}
减速器
export const reducer: Reducer<UsersState> = (state = initialState, action) => {
switch (action.type) {
case UserActionTypes.GET_USERS: {
return {...state, loading: true, data: action.payload }
}
default: {
return state
}
}
}
export { reducer as usersReducer }
用户列表组件
class AdminUsersPage extends Component<AllProps, AdminUserPageState> {
constructor(props: AllProps) {
super(props)
}
state: AdminUserPageState = {
filters: {
name: ''
}
}
componentDidMount() {
const { data } = this.props
if (!data || data.content === undefined) {
// Gettign the users properly.
this.props.getUsers()
}
}
renderUSers() {
if (this.props.data.content !== undefined) {
return this.props.data.content.map((user, index) => {
return (
<tr key={index}>
<td>{ user.name }</td>
</tr>
)
})
}
}
setFilter(e: React.ChangeEvent<HTMLInputElement>) {
this.setState({
filters: {
name: e.target.value
}
})
// Requesting the users again but the action never get the filters
this.props.getUsers(this.state.filters)
}
render() {
return (
<div>
<input type="text" onChange={ e => this.setFilter(e) } value={ this.state.filters.name } />
<Table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
{this.renderUSers()}
</tbody>
</Table>
</div>
)
}
}
const mapStateToProps = ({ users }: ApplicationState) => {
return {
loading: users.loading,
data: users.data,
errors: users.errors
}
}
const mapDispatchToProps = (dispatch: Dispatch) => ({
getUsers: () => dispatch(getUsers())
})
export default connect(
mapStateToProps,
mapDispatchToProps,
)(AdminUsersPage)
我认为我对React / redux的工作流程不了解,也不确定发送过滤器的严格方法是否将其设置为状态(我想这不是一个坏习惯,我认为m将具有多个过滤器)
答案 0 :(得分:0)
const mapDispatchToProps = (dispatch: Dispatch) => ({
getUsers: () => dispatch(getUsers())
});
根据上述声明,getUser
已注册以调度其操作,而没有任何参数传递给它。
因此,使用getUsers
调用filter
不会将filter
转发给动作创建者。
要注册它以便转发传递给它的参数,您需要使组件接收的函数接受一个参数并将其转发给动作创建者例如
const mapDispatchToProps = (dispatch: Dispatch) => ({
getUsers: filter => dispatch(getUsers(filter))
});