Reducx-redex-reduced v4/v5 푸시슈트가 thunk 동작 내부에서 작동하지 않음
인index.js
직접 푸시 또는 디스패치가 효과적임:
...
import { push } from 'react-router-redux'
const browserHistory = createBrowserHistory()
export const store = createStore(
rootReducer,
applyMiddleware(thunkMiddleware, routerMiddleware(browserHistory))
)
// in v5 this line is deprecated
export const history = syncHistoryWithStore(browserHistory, store)
history.push('/any') // works well
store.dispatch(push('/any')) // works well
ReactDOM.render((
<Provider store={store}>
<Router history={history}>
<App />
</Router>
</Provider>
), document.getElementById('root'))
App.js
class App extends Component {
render() {
return (
<div className="app">
<Switch>
<Route path="/" component={Main} />
<Route path="/any" component={Any} />
</Switch>
</div>
);
}
}
export default withRouter(connect(/*...*/)(App))
에 있어서redux-thunk
액션 모든 시도는 URL을 다시 쓰지만 다시 쓰지는 않음으로 종료됨
...
export function myAction(){
return (dispatch) => {
// fetch something and then I want to redirect...
history.push('/any') // change url but not re-render
dispatch(push('/any')) // change url but not re-render
store.dispatch(push('/any')) // change url but not re-render
}
}
이것myAction
fetchau를 안쪽으로 불러야 하고 성공 후에 방향을 바꾸어야 한다.
만약 내가 달리면this.props.history.push('/any')
컴포넌트 안에서는 작동한다! 하지만 나는 성공한 후에 내부로 리디렉션을 실행해야 한다.fetch()
나는 모든 구성 요소들을 로 포장하려고 했다.withRouter
또는Route
, 그러나 돕지 않았다.
주입하다history
구성 요소에 개체를 넣고 다음과 같이 푸시하십시오.
import { withRouter } from 'react-router-dom'
import { connect } from 'react-redux'
@withRouter
@connect(({auth})=>({auth}))
class App extends Component {
// on redux state change
componentWillReceiveProps(nextProps) {
if(!nextProps.auth)
this.props.history.push('/login')
}
render() {
return (
<div>
<Button
// on button click
onClick={this.props.history.push('/')}
>
Home page
</Button>
</div>
);
}
}
구성 요소(고마운 @oklas)에 successel fetch()의 상태를 위임하여 해결했다.history.push()
또는<Redirect>
작업:
{this.props.fetchSuccessfull && <Redirect to="/any" />}
그러나 여전히 thunk 액션으로부터 직접 push()를 호출하여 더 나은 해결책을 기다리고 있다.
그럼 내가 또 다른 완벽하지 않은 해결책을 제출하도록 하지. 파견에 있는 역사 대상을 행동에 옮기면서 말이야.초보적인 해결책이지만 IMHO는 이해하기 간단하다(따라서 소프트웨어 개발에서 가장 중요한 것을 유지하기가 간단하다).
<BrowserRouter>를 사용하면 모든 React-components가 소품 안에 이력이 있게 된다.아주 편리하다.그러나 문제 설명에서 언급한 바와 같이 Redex-Tunk에 대한 조치와 같이 React 구성 요소 외부로 이동하십시오.
<라우터>로 돌아가는 대신 브라우저루터를 고수하기로 했다.
- 기록 오브젝트는 대응 구성요소 외부에서 액세스할 수 없음
- 나는 <로터>로 돌아가서 리액션루터-리벤스 같은 것을 사용하는 것을 좋아하지 않았다.
남은 옵션만 히스토리 오브젝트를 액션에 전달하는 것이다.
Auth-ForgotPassword 구성 요소:
const submitHandler = (data) => {
dispatch(authActions.forgotpassword({data, history:props.history}));
}
동작함수에서
export const forgotpassword = ({forgotpasswordData, history}) => {
return async dispatch => {
const url = settings.api.hostname + 'auth/forgotpassword'; // Go to the API
const responseData = await fetch(
url,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(forgotpasswordData),
}
);
history.push('/auth/forgotpassword/success');
}
}
그리고 이제 우리 모두는 마지막 우아한 해결책을 기다린다 :-)
'IT이야기' 카테고리의 다른 글
리액트-라우터 V6 "url 변경은 있지만 구성 요소가 렌더링하지 않음" (0) | 2022.03.19 |
---|---|
".../node_modules/rxjs/Rx"에 내보낸 멤버 '던지기'가 없음 (0) | 2022.03.19 |
Vuex Store Getter가 새 값을 제 시간에 받지 못함.isoWeek() (0) | 2022.03.19 |
react-router 렌더 함수의 URL 매개 변수에 액세스 (0) | 2022.03.19 |
테스트하는 동안 MemoryRouter를 사용하여 경로로 이동할 수 없음 (0) | 2022.03.19 |