जब मैं घटक में इसे एक्सेस करने का प्रयास करता हूं तो state
में props
में परिवर्तन का प्रचार नहीं करने के बारे में रिएक्ट रिडक्स के साथ "क्लासिक" समस्या है।
यहां मैंने वह पढ़ा है
99.9% समय, ऐसा इसलिए है क्योंकि आप गलती से डेटा को बदल रहे हैं, आमतौर पर आपके रेड्यूसर में
क्या आप मुझे बता सकते हैं कि मैं क्या गलत कर रहा हूँ? सरणी में निर्दिष्ट ऑब्जेक्ट की संपत्ति की गहरी प्रतिलिपि कैसे करें यह अच्छा तरीका है?
नोट: रिटर्न स्टेटमेंट में रिड्यूसर में राज्य स्पष्ट रूप से सही ढंग से बदल गया है (इसे डिबग किया गया है)
reducer:
case 'TOGGLE_SELECTED_TAG':
const toggledTagId = action.payload;
const index = findItemById(state.tags, toggledTagId);
const newTags = state.tags.slice(0);
if(index >= 0)
{
newTags[index] = Object.assign(
state.tags[index],
{selected: !state.tags[index].selected});
state.tags = newTags;
}
return Object.assign({}, state);
घटक:
import React from 'react';
import { Button, FormControl, Table, Modal } from 'react-bootstrap';
import { connect } from 'react-redux';
import axios from 'axios';
import {selectTagAction} from '../../actions/actions'
@connect((store) => {
return {
tags: store.TagsReducer.tags,
}
})
export default class AssignTag extends React.Component {
constructor(props) {
super(props);
this.handleTagClick = this.handleTagClick.bind(this);
}
handleTagClick(element) {
debugger;
this.props.dispatch(selectTagAction(element));
}
render() {
const tags = this.props.tags;
console.log(tags);
const mappedTags = tags.map(tag => {
return (
<div className="col-sm-12" key={tag.id} onClick={() => this.handleTagClick(tag.id)}
style={{background: this.getBackgroundColor(tag.selected)}}>
<span>{tag.name}</span>
</div>
)
})
// code continues
}
}
2 जवाब
आप वास्तव में राज्य को बदल रहे हैं। ये कोशिश करें:
case 'TOGGLE_SELECTED_TAG':
const toggledTagId = action.payload;
const index = findItemById(state.tags, toggledTagId);
let newTags = state;
if( index >= 0 )
{
newTags[index] = Object.assign(
{},
state.tags[index],
{ selected: !state.tags[index].selected }
);
//state.tags = newTags; This line essentially mutates the state
return Object.assign( {}, state, { tags: newTags });
}
return state;
राज्य के उत्परिवर्तन से बचने के लिए एक और समाधान है अपने रेड्यूसर में ES6 शॉर्टहैंड का उपयोग करना:
.... return { ...state, tags : newTags };
संबंधित सवाल
नए सवाल
reactjs
प्रतिक्रिया उपयोगकर्ता इंटरफ़ेस के निर्माण के लिए एक जावास्क्रिप्ट पुस्तकालय है। यह एक घोषणात्मक, घटक-आधारित प्रतिमान का उपयोग करता है और इसका उद्देश्य कुशल और लचीला दोनों है।