如何使用redux-thunk存储在html元素中显示JSON数据



我正在尝试使用Redux和Redux -thunk中间件来修改状态更改,并使用异步操作来发送数据和从服务器接收数据。我创建了自己的rails api,它在我的网页的控制台日志中返回JSON数据,但我想知道如何在我的html中的div中呈现此数据。我意识到这可能不是以最好的方式编码,任何帮助重写也会很感激!

这是我的app.js文件的开始

import React from "react";
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom'
import "./assets/style.css";
import Quiz from "./components/quiz"
import Home from "./components/home";
import Result from "./components/Result";
import { useEffect } from "react";

function App() {
useEffect (() => {
fetch("http://127.0.0.1:3000/questions")
.then(resp => resp.json())
.then(console.log);
},[])
return (
<div className="App">
<Router>
<Switch >
<Route exact path="/">
<Home />
</Route>
{ <Route exact path="/quiz">
<Quiz/>
</Route>}
<Route exact path="/result">
<Result />
</Route>
</Switch>
</Router>
</div>
);
}
export default App

这是我的index.js

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from 'react-redux';
import { createStore, applyMiddleware} from 'redux';
import thunk from 'redux-thunk';
import quizReducer from './store/reducers/reducer'
import "./assets/style.css";
import App from "./App";

const store = createStore(quizReducer, applyMiddleware(thunk))
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
)

这是我的action/reducer

actions.js

export const getQuestion = (question) => ({type: "GOT_QUIZ", payload: question})
export const fetchQuestion = () => {
return (dispatch) => {
fetch(url)
.then(resp => resp.json())
.then(question => {
dispatch(getQuestion(question))
})
}
}
export const createQuestion = (question) => {
return () => {
const configObj = {
method: 'POST',
question: JSON.stringify(question)
}
fetch(url, configObj)
.then(resp => resp.json())
.then(json => {
console.log(json)
})
}
}

reducer.js

export default function quizReducer(state = {questionBank: []}, action){
switch (action.type){
case "GOT_QUIZ":
return {...state, questionBank: action.payload}
default:
return state
}
}

假设您的减速器和操作是正确的,您需要在您的组件中做两件事。

1)初始化Fetch

import {useDispatch} from 'react-redux';
import {fetchQuestion} from './actions';
const dispatch = useDispatch();
useEffect (() => {
dispatch(fetchQuestion());
}, []);

这将在组件第一次挂载时调用一次fetchQuestionsthunk。

2)访问数据

import {useSelector} from 'react-redux';
const questions = useSelector(state => state.questionBank);

这将访问您的存储中的问题数组,并在存储状态更新时自动响应更改。

可能步骤1进入App,步骤2进入QuizResult。或者这两个步骤都在App中,您通过props传递数据。

相关内容

  • 没有找到相关文章

最新更新