reducer 的参数不会在调度时更新
parameter for reducer will not update at dispatch
我认为我的代码是正确的,它会检查 QueryString 是否未定义。如果是,则 'thePath' 从配置文件中获取值。如果 QueryString 有一个值(这意味着不再是未定义的),那么让 'thePath' 的值成为 QueryString。它可以工作,但它不会在函数的 return(dispatch) 部分得到更新。为什么?
该函数用于根据axios的结果设置不同的动作,最终成为reducer的一部分,redux store。
export let fetchingBook = (QueryString) => {
let thePath;
if (QueryString === undefined) {
thePath = process.env.REACT_APP_GATEWAY_BOOK_PATH
}
else
if (QueryString !== undefined) {
thePath = QueryString
}
console.log("thePath : " + thePath);
return (dispatch) => {
console.log("came to return dispatch first time, does not come here the second time.. why?");
dispatch(fetch_BOOK_Request())
axios.get(thePath)
.then(response => {
const BookDATA = response.data
dispatch(fetch_BOOK_Success(BookDATA))
})
.catch(error => {
const ErrorMsg = error.message
dispatch(fetch_BOOK_Failure(ErrorMsg))
})
}
}
更新:发送到哪里
const dispatching = dispatch => {
return {
// following is for another reducer
goFindByPlanNumber__functionalProp: planNum => dispatch({ type: "SEARCH_BY_PLAN_NUMBER", txt: planNum }, fetchingBook(planNum)),
//calling or dispatching fetchingBook here. it was added in the component using import
fetchingBook__functionalProp:(planNum)=> dispatch(fetchingBook(planNum))
}
}
这是一个基本示例,说明如何使用 redux thunk 执行异步操作(我制作了行为类似于 thunk 的中间件)
const { Provider, connect } = ReactRedux;
const { createStore, applyMiddleware } = Redux;
const defaultState = { val: 0 };
const store = createStore(
(state = defaultState, action) => {
//reducer
if (action.type === 'OK') {
return {
...state,
val: state.val + 1,
};
}
if (action.type === 'DATA') {
return {
...state,
data: action.payload,
};
}
return state;
},
defaultState,
//somple redux thunk like middleware
applyMiddleware(store => next => action => {
if (typeof action === 'function') {
return action(store.dispatch, store.getState);
}
return next(action);
})
);
class App extends React.Component {
state = { selectedId: 0 };
render() {
return (
<div>
<div>
<button onClick={this.props.action}>
{this.props.val}
</button>
</div>
<div>
<select
value={this.state.selectedId}
onChange={e => {
this.setState({ selectedId: e.target.value });
this.props.getData(e.target.value);
}}
>
<option value={0}>select id</option>
{[1, 2, 3, 4, 5].map(id => (
<option key={id} value={id}>
{id}
</option>
))}
</select>
</div>
<div>
data is:{' '}
{JSON.stringify(this.props.data, undefined, 2)}
</div>
</div>
);
}
}
const ConnectedApp = connect(
state => ({ val: state.val, data: state.data }), //map state to props
{
//map dispatch to props
action: () => (dispatch, getState) => {
//thunk like action
console.log(
'in action, current state is',
getState()
);
dispatch({ type: 'OK' });
let timesExecuted = 0;
const timer = setInterval(() => {
timesExecuted++;
dispatch({ type: 'OK' });
if (timesExecuted > 3) {
clearInterval(timer);
}
}, 1000);
},
getData: id => dispatch => {//get data action
//you can dispatch loading action
fetch(
`https://jsonplaceholder.typicode.com/todos/${id}`
)
.then(response => response.json())
.then(data =>
dispatch({ type: 'DATA', payload: data })
);
},
}
)(App);
ReactDOM.render(
<Provider store={store}>
<ConnectedApp />
</Provider>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<div id="root"></div>
我认为我的代码是正确的,它会检查 QueryString 是否未定义。如果是,则 'thePath' 从配置文件中获取值。如果 QueryString 有一个值(这意味着不再是未定义的),那么让 'thePath' 的值成为 QueryString。它可以工作,但它不会在函数的 return(dispatch) 部分得到更新。为什么?
该函数用于根据axios的结果设置不同的动作,最终成为reducer的一部分,redux store。
export let fetchingBook = (QueryString) => {
let thePath;
if (QueryString === undefined) {
thePath = process.env.REACT_APP_GATEWAY_BOOK_PATH
}
else
if (QueryString !== undefined) {
thePath = QueryString
}
console.log("thePath : " + thePath);
return (dispatch) => {
console.log("came to return dispatch first time, does not come here the second time.. why?");
dispatch(fetch_BOOK_Request())
axios.get(thePath)
.then(response => {
const BookDATA = response.data
dispatch(fetch_BOOK_Success(BookDATA))
})
.catch(error => {
const ErrorMsg = error.message
dispatch(fetch_BOOK_Failure(ErrorMsg))
})
}
}
更新:发送到哪里
const dispatching = dispatch => {
return {
// following is for another reducer
goFindByPlanNumber__functionalProp: planNum => dispatch({ type: "SEARCH_BY_PLAN_NUMBER", txt: planNum }, fetchingBook(planNum)),
//calling or dispatching fetchingBook here. it was added in the component using import
fetchingBook__functionalProp:(planNum)=> dispatch(fetchingBook(planNum))
}
}
这是一个基本示例,说明如何使用 redux thunk 执行异步操作(我制作了行为类似于 thunk 的中间件)
const { Provider, connect } = ReactRedux;
const { createStore, applyMiddleware } = Redux;
const defaultState = { val: 0 };
const store = createStore(
(state = defaultState, action) => {
//reducer
if (action.type === 'OK') {
return {
...state,
val: state.val + 1,
};
}
if (action.type === 'DATA') {
return {
...state,
data: action.payload,
};
}
return state;
},
defaultState,
//somple redux thunk like middleware
applyMiddleware(store => next => action => {
if (typeof action === 'function') {
return action(store.dispatch, store.getState);
}
return next(action);
})
);
class App extends React.Component {
state = { selectedId: 0 };
render() {
return (
<div>
<div>
<button onClick={this.props.action}>
{this.props.val}
</button>
</div>
<div>
<select
value={this.state.selectedId}
onChange={e => {
this.setState({ selectedId: e.target.value });
this.props.getData(e.target.value);
}}
>
<option value={0}>select id</option>
{[1, 2, 3, 4, 5].map(id => (
<option key={id} value={id}>
{id}
</option>
))}
</select>
</div>
<div>
data is:{' '}
{JSON.stringify(this.props.data, undefined, 2)}
</div>
</div>
);
}
}
const ConnectedApp = connect(
state => ({ val: state.val, data: state.data }), //map state to props
{
//map dispatch to props
action: () => (dispatch, getState) => {
//thunk like action
console.log(
'in action, current state is',
getState()
);
dispatch({ type: 'OK' });
let timesExecuted = 0;
const timer = setInterval(() => {
timesExecuted++;
dispatch({ type: 'OK' });
if (timesExecuted > 3) {
clearInterval(timer);
}
}, 1000);
},
getData: id => dispatch => {//get data action
//you can dispatch loading action
fetch(
`https://jsonplaceholder.typicode.com/todos/${id}`
)
.then(response => response.json())
.then(data =>
dispatch({ type: 'DATA', payload: data })
);
},
}
)(App);
ReactDOM.render(
<Provider store={store}>
<ConnectedApp />
</Provider>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<div id="root"></div>