您的代码似乎缺少 Redux 工作的一些关键元素。当您的搜索输入发生变化时,您需要分派 Redux 操作,从而更新存储。现在你只是设置本地状态SearchBar
当输入改变时。其次,你的减速器不会修改状态,它总是返回相同的数组。
沿着这些思路。
您的操作文件可能如下所示:
export const SEARCH = 'SEARCH';
export function search(value) {
return {type: SEARCH, value};
}
那么你的减速器可能看起来像这样:
import {SEARCH} from './actions';
const initialState = {contents: ['Mirististica', 'Vet'], value: '', works: []};
export default function reducer(state = initialState, action) {
switch(action.type) {
case SEARCH: {
const {value} = action;
const works = state.contents.filter((val) => val.includes(value));
return {...state, value, works};
}
default:
return state;
}
}
然后在你的SearchBar
:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {search} from './actions';
class SearchBar extends Component {
render() {
const {search, value} = this.props;
return (
<input
className="form-control"
placeholder = "Procurar Trabalho"
onChange={(e) => search(e.target.value)}
value={value} />
);
}
}
function mapStateToProps({works}) {
return {value: works.value};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({search}, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
Your WorkList
组件只需要监听更改works
在 Redux 商店中。
import React, { Component } from 'react';
import { connect } from 'react-redux';
class WorkList extends Component {
render() {
const {works} = this.props;
return (
<table className="table table-hover">
<thead>
<tr>
<th>Nome</th>
</tr>
</thead>
<tbody>{works.map((work) => <tr key={work}><td>{work}</td></tr>)}</tbody>
</table>
);
}
}
function mapStateToProps({works}) {
return {
works: works.works
}
}
export default connect(mapStateToProps)(WorkList);