2016-03-14 30 views
1

已解決:defaultValue行爲不像我想的那樣,我需要一個受控組件,請檢查有關受控組件的React文檔。瞭解Redux的生命週期,(初始Ajax加載不起作用)

我想要做什麼:在Ajax調用後,在表單字段中加載「owner」值。

的問題是: 「componentDidMount()」 函數不更新this.props.owner。 「所有者」的值,當你點擊「編輯」中的行列表在之前的組件,之後第二次點擊的所有作品完美,但沒有在第一負載從而出現多種形式對話中。

我AppoModal組件:

class AppoModal extends Component { 
    constructor(props) { 
    super(props); 
} 

/** Load 'owner' in the form **/ 
componentDidMount() { 
    let action = fetchAppos(this.props.routeParams.id); 
    this.props.dispatch(action); 
} 

render() { 
    return (
     <div> 
     <input name="owner" defaultValue={this.props.owner} /> 
     </div> 
    ); 
    } 
}; 

AppoModal.propTypes = { 
    owner: PropTypes.string.isRequired 
}; 
AppoModal.defaultProps = { 
    owner: 'incorrect initial props owner' 
}; 

function mapStateToProps(state) { 
    return { 
    owner: state.rootReducer.appointments_rdcer.owner 
    } 
} 
export default connect(mapStateToProps)(AppoModal); // binding React-Redux 

我actions.js文件:

export function fetchAppos(appo_id=0) { 
    return function (dispatch) { 
    console.log('fecthAppos Action appo_id >>>>>' + appo_id); 
    let data = { 
     method: 'POST', 
     credentials: 'same-origin', 
     mode: 'same-origin', 
     body: JSON.stringify({ 
     appoid: appo_id 
     }), 
     headers: { 
     'Accept':  'application/json', 
     'Content-Type': 'application/json', 
     'X-CSRFToken': cookie.load('csrftoken') 
     } 
    } 
    return fetch('/appointments/get_appos', data) 
     .then(response => response.json()) // promise 
     .then(json = dispatch(receiveAppo(json))) 
    } 
    }; 
    // after fetchAppos, the API Ajax call 
    function receiveAppo(appoArrayProp) { 
    return { 
     type: GET_ONE_APPO, 
     appoArrayProp: appoArrayProp.shift() 
    } 
    } 

減速器殼體:

case RECEIVE_ONE_APPO: 
    return Object.assign({}, state, { 
    owner: action.appoArrayProp.owner 
    }); 

的錯誤結果(應爲 「格林兄弟」):

enter image description here

所以我定義的「this.props.owner」爲「不正確的初始道具老闆」,但據我瞭解,componentDidMount應該後執行整個DOM被加載,然後觸發:

this.props.dispatch(action) 

,然後減速應該設置「格林兄弟」爲this.props.owner價值,但這不會發生。我在Reducer中看到「Grimms」作爲所有者的值,所以我不會追蹤爲什麼this.props.owner永遠不會更新。

回答

1

在渲染()函數:

render() { 
    return (
     <div> 
     <input name="owner" defaultValue={this.props.owner} /> 
     </div> 
    ); 
    } 

您使用默認值,它僅用於設置初始值渲染(在你的情況是你指定的defaultProps)。要更新的輸入值,你必須使用一個控制<input>組件

您的<input>組件僅通過提供值prop即可成爲受控組件。因此,定義這樣您的組件應該工作:

render() { 
    return (
     <div> 
     <input name="owner" value={this.props.owner} /> 
     </div> 
    ); 
    } 

約受控和非受控組件的詳細信息,請參閱https://facebook.github.io/react/docs/forms.html

+0

謝謝!是的默認值的行爲問題。 – aarkerio