Javascript 如何在Redux中创建合适的搜索方法?
我是Redux的新手,需要搜索方面的帮助 我需要使用一些api获取搜索结果。此api为我提供了以下端点:Javascript 如何在Redux中创建合适的搜索方法?,javascript,reactjs,api,redux,fetch,Javascript,Reactjs,Api,Redux,Fetch,我是Redux的新手,需要搜索方面的帮助 我需要使用一些api获取搜索结果。此api为我提供了以下端点: POST /search/ GET /search/:id/results 所以我需要做: 使用我的搜索数据发出post请求 然后,当我得到它的响应时,我获取一个特定的搜索id 使用此id发出get请求以获取结果 我尝试通过以下方式获取结果: const FETCH_RESULTS_SUCCESS = 'FETCH_RESULTS_SUCCESS'; const initialState
POST /search/
GET /search/:id/results
所以我需要做:
const FETCH_RESULTS_SUCCESS = 'FETCH_RESULTS_SUCCESS';
const initialState = {
results: []
};
export default function reducer(state = initialState, action) {
switch (action.type) {
case FETCH_RESULTS_SUCCESS:
return Object.assign([], state, { results: action.results });
default:
return state;
}
}
export const fetchResults = id => dispatch => {
return
fetch(`/search/${id}/results`, {
method: 'get',
'Content-Type': 'application/json'
})
.then(res => res.json())
.then(results => {
dispatch({
type: FETCH_RESULTS_SUCCESS,
results
})
})
export const createSearch = data => dispatch => {
return fetch('/search/', {
method: 'post',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => data.id)
.then(id => dispatch(fetchResults(id)))
}
问题是它给我的结果是空的。但是如果我把一些真实的搜索id(假设我们在db中有以前的搜索)像这样dispatch(fetchResults(15)
它会给我结果
为什么这样传递身份证不起作用
.then(data => data.id)
.then(id => dispatch(fetchResults(id)))
我的方法行吗?或者你会建议我以其他方式用这样的api实现搜索吗
p.S.代码可能有一些拼写错误。您使用的是redux thunk吗?是的,当然。您可以在一次操作中进行两次调用。只需将承诺链接起来。@Oridori谢谢,我刚刚尝试过,但运气不好。我想问题在于如何将id传递给下一次获取。我如何将id从post请求响应传递给下一个get请求?这不是解决问题的方法lem。您不需要为此执行任何操作。将
dispatch(fetchResults(id))
替换为console.log(id)
。你看到了什么?你在使用redux thunk吗?是的,当然。你可以在一次操作中进行两次调用。只需将承诺链接起来。@Oridori谢谢,我刚刚尝试过,但运气不好。我想问题在于如何将id传递给下一次获取。我如何将id从请求后响应传递给下一次获取请求?这不是你问题的解决方案。你是不需要为此执行任何操作。将dispatch(fetchResults(id))
替换为console.log(id)
。您看到了什么?