我在页面上有一个实时过滤器结构。我输入的数据保存在我的状态中,同时也作为 URL 查询保存,这样当有人打开 URL 中包含过滤器的页面时,就已经选择了正确的过滤器。
我正在努力寻找一种稳定的方法来保持这两者同步。目前,我在加载时从 URL 获取数据,并在每次更改状态时在 URL 中设置数据,但这种结构几乎不可能重用所涉及的组件,并且错误很容易导致无限循环,这实际上也是不可能扩大。是否有更好的架构来保持这些同步?
最佳答案
我建议通过查询参数管理 View 中过滤器的状态。如果您使用react-router,您可以使用查询参数而不是状态,并在渲染方法中获取 View 元素所需的参数。更改过滤器后,您需要实现重定向。为了更方便,最好使用 qs module 。通过这种方法,您还将收到一个用于向后端请求的现成参数。
示例容器:
const initRequestFields = {someFilterByDefault: ''};
class Example extends Component{
constructor(props) {
super(props);
this.lastSearch = '';
}
componentDidMount() {
this.checkQuery();
}
componentDidUpdate() {
this.checkQuery();
}
checkQuery() {
const {location: {search}, history} = this.props;
if (search) {
this.getData();
} else {
history.replace({path: '/some-route', search: qs.stringify(initRequestFields)});
}
}
getData() {
const {actionGetData, location: {search}} = this.props;
const queryString = search || `?${qs.stringify(initRequestFields)}`;
if (this.lastSearch !== queryString) {
this.lastSearch = queryString;
actionGetData(queryString);
}
}
onChangeFilters = (values) => {
const {history} = this.props;
history.push({path: '/some-route', search: qs.stringify(values)});
};
render() {
const {location: {search}} = this.props;
render(<Filters values={qs.parse(search)} onChangeFilers={this.onChangeFilters} />)
}
}
此逻辑最好保留在将值传递给组件的最高容器中。
获取更多信息:
Query parameters in react router
关于javascript - react 保持数据同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56006023/