React Redux Url更改事件/体系结构

时间:2017-09-16 09:35:50

标签: reactjs events redux react-router react-redux

我正在使用React构建应用程序。如果有人想搜索以下情况:

  1. 状态已更新:this.props.Address.selectedAddress
  2. 点击搜索按钮,触发搜索事件并更改我的网址:

    this.props.handleSearch(address);
    let city = format_city(this.props.Address.selectedAddress);
    browserHistory.push('/searchfor/'+city);
    
  3. 工作正常。现在我希望如果有人在应用程序中添加新URL,也会触发搜索事件。到目前为止我做了什么:

    class ResultsList extends React.Component {
     constructor(props) {
      super(props);
    }
    
    componentDidMount() {
        this.unlisten = browserHistory.listen( (location) =>  {
            console.log('route changes');
            if (this.selectedAdressNOTMatchUrl()){
                this.handelAdressSearch()
            }
    
        });
    
    }
    componentWillUnmount() {
        this.unlisten();
    
    }
    

    现在问题是click事件更改了url,结果列表组件认为它必须处理此事件:触发搜索并更新selectedAddress。

    我真的认为这是一个糟糕的设计我是如何做到的。当然我可以添加一个时间戳或类似的东西来确定browserHistory.push(' / searchfor /' + city);在url change事件被触发之前发生,但这有点难看。

    感谢每一个想法!

    这是我的设置:

    export const store = createStore(
    reducers,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
    compose(
        applyMiddleware(
            thunkMiddleware,
            promiseMiddleware()),
        autoRehydrate()
    )
    );
    
    const persistor = persistStore(store, {storage: localForage});
    render(
    <Provider store={store} persistor={persistor}>
        <Router history={browserHistory}>
            <Route path="/" component={Home}/>
            <Route path="/searchfor/:city" component={Suche}/>
        </Router>
    </Provider>,
    
    PS:还有一个评论 我试过react-router-redux。它保存了url状态。但它没有解决问题。例如,我输入一个新网址。然后触发事件LOCATION_CHANGE。但在此之后,我的persist / REHYDRATE事件被触发了。这样网址就会改变。这使得行为更加糟糕......

    PPS:使其更清晰。一切正常。我想再添加一个功能。如果用户自己输入了新的URL,那么如果他点击搜索按钮,应用程序应该以相同的方式处理。但这似乎是一个很难的出价,因为在我的应用程序中,再水化事件被解雇......

1 个答案:

答案 0 :(得分:0)

不确定redux-persist(&#34;补水&#34;)是如何起作用的,所以也许我错过了一些至关重要的东西..但我认为通过连接你可以解决你的问题是可能的ResultsList组件到Redux,以便它将react-router url-parameter传递给它,类似这样的

// ownProps is be the props passed down from the Route, including path params
const mapStateToProps = (state, ownProps) => {
   return {
     searchTerm: ownProps.city,  // the url param
     results: state.searchResults // after a manual url entry this will be undefined

  }
}

const mapDispatchToProps = (dispatch) => {
    return { 
     handleSearch: searchTerm => dispatch(searchAction(searchTerm)) 
    };
};

(那种代码应该是according to these docs here

然后,在ResultsList内,您可以启动搜索。

componentDidMount() {
  const {searchTerm, handleSearch} this.props;

     handleSearch(searchTerm);
  }
}

render() {
  const {results} = this.props;
  return !results ?
    <p>Loading..</p> : 
    <div>
     { results.map(renderResultItem) }
    </div>
}

这样,组件就不必关心URL-param来自手动输入的URL,还是来自搜索页面的编程推送URL。