简体   繁体   English

在React + Rails中使用show路线

[英]Using the show route in react + rails

I'm building out a simple quiz app with a rails api rendering the questions in json and react pulling them in. However I'm not very experienced with react and I'm having trouble working out how to go about getting one question at a time displayed on the screen as the display is the same going to localhost:3000 or localhost:3000/questions/1. 我正在使用Rails API构建一个简单的测验应用程序,以json形式呈现问题并做出反应,将它们拉进去。但是我对React的经验不是很丰富,我很难确定如何在一个问题上解决一个问题。屏幕上显示的时间与到达localhost:3000或localhost:3000 / questions / 1的时间相同。 Any advice on how to get it using the show method when appropriate instead of index for everything would be really appreciated. 任何有关在适当的时候使用show方法代替索引来获取所有内容的建议都将受到赞赏。

  componentDidMount() {
    axios.get('http://localhost:3001/api/v1/questions.json')
    .then(response => {
      console.log(response)
      this.setState({questions: response.data})
    })
    .catch(error => console.log(error))
  }

your index route should show all the questions 您的index路线应显示所有问题

So: 所以:

def index
    questions = Question.all
    however_you_render_json(questions)
end

And your show route should take the id from the URL and show one questions from that 您的show路线应从网址中获取ID,并从中显示一个问题

def show
    question = Question.find(params[:id])
    however_you_render_json(question)
end

in your routes.rb file you should have 在你的routes.rb文件中

resources :users

which which automatically create the required routes, you can run bundle exec rake routes in rails console to verify the URI patterns 它会自动创建所需的路由,您可以在rails控制台中运行bundle exec rake routes来验证URI模式

On the React end, the requests should be: axios.get('http://localhost:3001/api/v1/questions/) for index or axios.get('http://localhost:3001/api/v1/questions/1) for show. 在React端,请求应为: axios.get('http://localhost:3001/api/v1/questions/)用于索引或axios.get('http://localhost:3001/api/v1/questions/1)显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM