gpt4 book ai didi

node.js - React 中 fetch 不返回数据

转载 作者:太空宇宙 更新时间:2023-11-04 03:24:19 26 4
gpt4 key购买 nike

我是 react 新手,我很难从列表中获取单本书的数据,无法通过 axios 的 get 方法传递。我认为这与网址有关,但我一直无法修复它。

这是我的代码:

export function loadBook(book){
return dispatch => {
return axios.get('http://localhost:3000/api/books/book/:id').then(book => {
dispatch(loadBookSuccess(book.data));
console.log('through!');
}).catch(error => {
console.log('error');
});
};
}

//also tried this
export function loadBook(id){
return dispatch => {
return axios.get('http://localhost:3000/api/books/book/' + {id}).then(book => {
dispatch(loadBookSuccess(book.data));
console.log('through!');
}).catch(error => {
console.log('error');
});
};
}

包含指向每本书的变量链接的 HTML 代码

 <div className="container">
<h3><Link to={'/book/' + book._id}> {book.title}</Link></h3>
<h5>Author: {book.author.first_name + ' ' + book.author.family_name}</h5>
<h4>Summary: {book.summary}</h4>
<BookGenre genre={genre} />

</div>

route 的链接:

<Route path="/book/:id" component={BookPage} />

编辑:书籍组件的代码

class BookPage extends React.Component{
render(){
const book = this.props;
const genre = book.genre;
console.log(book);

return(
<div>
<div>
<h3> {book.title}</h3>
<h5>Author: {book.author.first_name + ' ' + book.author.family_name}</h5>
<h4>Summary: {book.summary}</h4>
<BookGenre genre={genre} />
</div>

</div>
);
}
}

BookPage.propTypes = {
book: PropTypes.object.isRequired
};

//setting the book with mapStateToProps
function mapStateToProps (state, ownProps){
let book = {title: '', author: '', summary: '', isbn: '', genre: []};
const bookid = ownProps.params._id;
if(state.books.length > 0){
book = Object.assign({}, state.books.find(book => book.id));
}
return {
book: book
};
}

function mapDispatchToProps (dispatch) {
return {
actions: bindActionCreators(loadBook, dispatch)
};
}



export default connect(mapStateToProps, mapDispatchToProps)(BookPage);

最佳答案

不要这样做:-

axios.get('http://localhost:3000/api/books/book/' + {id})

You should do like this:-

axios.get(`http://localhost:3000/api/books/book/${id}`)

So your action.js might look like this:-

export function loadBook(id){
const request = axios.get(`http://localhost:3000/api/books/book/${id}`);
return dispatch => {
request.then(book => {
dispatch(loadBookSuccess(book.data));
}).catch(error => {
console.log('error');
})
};
}

由于 id,您传递的它似乎是一个字符串,因此可以使用 ES6 模板字符串 连接它,并确保将字符串用反引号括起来。或者您可以通过 + 运算符来完成此操作,同时确保将 id 作为参数传递到 loadbook 函数中,以便您可以将其连接到您的 URL。

关于node.js - React 中 fetch 不返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46585538/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com