#javascript #reactjs #redux #react-redux
#javascript #reactjs #redux #реагировать-redux
Вопрос:
Я пытаюсь сопоставить массив объектов в моем приложении react js, я получаю свой ответ с помощью redux, что верно, проблема в том, что всякий раз, когда я использую mapstatetoprops
, и mapDispatchtoprops
он не отображает мои реквизиты в состояние, из-за которого iam становится неопределенным в моей консоли, кроме того, что я не могу сопоставить ответ вложенного массива, который я хочучтобы получить значение, которое находится внутри inputOptions
, как я могу исправить эти проблемы.
Мой компонент
import React, { Component } from "react";
import {
FormCardComponent,
TextInputComponent,
RadioInputComponent,
SelectComponent,
} from "../../components/index";
import IntlMessages from "../../common/constants/IntlMessages";
import frontPage from "./dummy";
import { TopBar } from "../../layouts/authLayout/components/index";
import { getEmsForms } from "../../redux/action/categories";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { Form } from "./form";
class DummyForm extends Component {
constructor(props) {
super(props);
this.state = {
field: "",
checkBox: "",
options: "",
radioField: "",
error: "",
data: frontPage,
};
}
componentDidMount() {
this.props.getEmsForms()
}
render() {
console.log('COMP',JSON.stringify(this.props.getEmsForms()));
return (
<React.Fragment>
<div className="col" style={{ marginTop: "50px" }}>
<React.Fragment>
<TextInputComponent
style={{ marginTop: "50px" }}
label={<IntlMessages id="profile.personal.field.name" />}
type="text"
placeholder={"Abdul"}
value={this.state.name}
onChange={(e) =>
this.setState({ name: e.target.value, error: "" })
}
/>
<select
className="custom-select"
id="inputGroupSelect01"
style={{ marginTop: "50px" }}
>
<option>
{/* {value.MinimumAge} */}
yes
</option>
<option>
{/* {value.MinimumAge} */}
yes
</option>
</select>
<div style={{ marginTop: "50px" }}>
<SelectComponent
style={{ marginTop: "50px" }}
name={"select2"}
value={this.state.select2}
label={
"Jeg vil gerne modtage en SMS når der er nyheder til mig"
}
onChange={(e) => this.setState({ select2: e.target.checked })}
/>
</div>
<div style={{ marginTop: "50px" }}>
{/* <RadioInputComponent
title="gender"
value={this.state.gender}
name={["male", "female", "other"]}
onChange={(e) => {
this.setState({ gender: e.target.value, error: "" });
}}
/> */}
<input
style={{
float: "left",
clear: "none",
margin: "3px",
}}
type="radio"
/>
<label style={{ padding: " 0px 1em 0px 8px" }}>
Jeg vil gerne modtage en SMS når der er nyheder til mig
</label>
</div>
<div className="row" style={{ marginTop: "50px" }}>
<div className="col d-flex justify-content-start">
<button className="btn-danger" onClick={this.toggleModal}>
Ja
</button>
</div>
<div className="col d-flex justify-content-end">
<button className="btn btn-success button-margin">Ja</button>
</div>
</div>
</React.Fragment>
</div>
</React.Fragment>
);
}
}
const mapStateToProps = (data) => ({
// user: data.authenticateUser.user,
// isAuthenticated: data.authUser,
getForms: data.categories.getForms,
});
const mapDispatchToProps = (dispatch) =>
bindActionCreators(
{
getEmsForms,
},
dispatch
);
export default connect(mapStateToProps, mapDispatchToProps)(DummyForm);
Мой ответ Api
{
"success": true,
"messages": "EMS Form",
"data": [
{
"question_id": 3,
"fieldName": "FirstName",
"order": 0,
"isRequired": true,
"isShown": true,
"isEditable": false,
"fieldLabelText": "First Name da",
"errorText": "First Name Error da",
"inputType": "textbox",
"inputOptions": [],
"inputOptionsCustom": []
},
{
"question_id": 4,
"fieldName": "LastName",
"order": 1,
"isRequired": true,
"isShown": true,
"isEditable": false,
"fieldLabelText": "First Name da",
"errorText": "First Name Error da",
"inputType": "textbox",
"inputOptions": [],
"inputOptionsCustom": []
},
{
"question_id": 2,
"fieldName": "Age",
"order": 2,
"isRequired": true,
"isShown": true,
"isEditable": false,
"fieldLabelText": "First Name da",
"errorText": "First Name Error da",
"inputType": "dropdown",
"inputOptions": [
{
"option_id": 7,
"text": "18",
"value": "18"
},
{
"option_id": 8,
"text": "19",
"value": "19"
},
{
"option_id": 9,
"text": "20",
"value": "20"
},
{
"option_id": 10,
"text": "21",
"value": "21"
},
{
"option_id": 11,
"text": "22",
"value": "22"
},
{
"option_id": 12,
"text": "23",
"value": "23"
}
],
"inputOptionsCustom": []
},
{
"question_id": 5,
"fieldName": "PhoneNumber",
"order": 3,
"isRequired": false,
"isShown": true,
"isEditable": false,
"fieldLabelText": "First Name da",
"errorText": "First Name Error da",
"inputType": "textbox",
"inputOptions": [],
"inputOptionsCustom": []
}
]
}
мое действие
export const getEmsForms = (data) => {
return async (dispatch) => {
dispatch(fullScreenLoader(true));
const api = new Axios();
let token = getToken();
console.log('token', JSON.stringify(token))
const response = await api.post(
GET_EMS_FORMS,
{
ems_id: EMS_ID,
},
{
Authorization: `Bearer ${token}`,
},API_URL2
);
// console.log(response);
console.log('res', JSON.stringify(response))
const { data } = response;
dispatch(fullScreenLoader(false));
dispatch({
type: GET_FORMS ,
payload: data,
});
};
};
мой редуктор
case GET_FORMS:
return {
...state,
forms: action,
};
Комментарии:
1. в случае
GET_FORMS
, когда вы, кажется, помещаете значениеaction
в свойствоforms
, но в тоmapsStateToProps
, к которому вы обращаетесьdata.categories.getForms
. Разве вы не должны получать доступ кforms
части вашего состояния?2. кроме того, нет JSX, который вы пытаетесь использовать
map
.3. @RameshReddy можете ли вы дать мне решение этой проблемы
4. Можете ли вы ответить на мои вопросы выше? Вы просто обращаетесь к неправильным свойствам.
5. Я исправил это, и теперь я получаю ответ
getForms: data.categories.forms,
Ответ №1:
Вы пытаетесь получить доступ data.categories.getForms
, но в вашем редукторе вы сопоставляете его forms
. Также вы хотите установить значение action.payload
to .forms
, а не все действие.
Итак, ваш редуктор должен выглядеть так:
case GET_FORMS:
return {
...state,
forms: action.payload,
};
и ваш mapStateToProps
const mapStateToProps = (data) => ({
user: data.authenticateUser.user,
isAuthenticated: data.authUser,
forms: data.categories.forms,
});
Комментарии:
1. это добавит
forms
свойство к реквизиту компонента, но оно по-прежнему указывает наdata.categories.getForms
so, это не устраняет проблему.2. я не получаю никаких данных в своем
mapDispatchToProps
3. Ах, извините, это было то, что я пропустил после копирования-вставки фрагмента