我正在尝试将 API 到存储的响应获取,以便任何组件都可以使用它。 在这种情况下,我希望能够将响应中的所有主体用作可以传递给组件以呈现其值的 prop
关于我应该怎么做才能从响应中获取数据并呈现它的任何想法? 也许我错过了一个 redux 步骤?
<小时 />减速机
export default (state=[], action) => {
switch (action.type) {
case 'FETCH_CV' :
return [...state, action.paylaod];
default:
return state;
}
动作创建者
import DiagnoseMl from '../Components/API/DiagnoseMl';
export const fetchCv= (formData) => async dispatch => {
const response = await DiagnoseMl.post('/d', formData);
dispatch({type: 'FETCH_CV', payload: response.data});
};
React 组件
import React from "react";
import styled from "styled-components";
import {connect} from 'react-redux';
import {fetchCv} from '../Actions';
import Example from '../Components/ReactToPrint'
class DataList extends React.Component{
state = {
// Initially, no file is selected
selectedFile: null
};
// On file select (from the pop up)
onFileChange = event => {
// Update the state
this.setState({ selectedFile: event.target.files[0] });
};
// On file upload (click the upload button)
onFileUpload = () =>{
// Create an object of formData
const formData = new FormData();
// Update the formData object
formData.append(
"file",
this.state.selectedFile
);
// Details of the uploaded file
console.log(this.state.selectedFile);
this.props.fetchCv(formData);
};
render(){
return (
<Container>
<Uploader>
<input id="uploadBtn" accept="application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document" type="file" onChange={this.onFileChange} />
<button onClick={this.onFileUpload}>
Cargar Archivo
</button>
</Uploader>
***<Example/>*** //i want to use the reponse in this component
</Container>
)
}
}
// our state object will have a prop called data, that contains all of the data return from the reducer
const mapStateToProps = (state) => {
return { posts: state.posts};
};
export default connect(mapStateToProps,{fetchCv})(DataList);
<小时 />店铺设置
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 reducers from './Reducers';
import App from './App';
const store = createStore(reducers, applyMiddleware(thunk));
ReactDOM.render(
<Provider store = {store}>
<App />,
</Provider>,
document.getElementById('root')
);
提前感谢!
编写一个名为选择器的函数,该函数将存储的状态作为参数,并从要使用的状态树中返回特定值。然后导入并调用 redux 的 useSelector(包装你的选择器)以获得最新的值。 然后,您可以在组件的 jsx 中打印该值,或将其传递到它适合的任何较低组件中。
旁注:我建议在你的操作方法中使用它,而不是仅仅将响应正文转储到有效负载中,而是更明确地映射你期望从响应中获得的属性。在化简器中,还要显式解构预期值。它将使您的代码更易于遵循。
选择器文件:
export const mySelector = (state) => {
// Calculate the value you want from state and return it here.
}
在组件文件中:
import { useSelector } from 'redux';
import { mySelector } from 'path-to-mySelector';
...
//Inside the component definition:
const someExpectedValueFromStore = useSelector(mySelector);